private static byte[] generateSignatureBlock( SignerConfig signerConfig, byte[] signatureFileBytes) throws InvalidKeyException, CertificateEncodingException, SignatureException { JcaCertStore certs = new JcaCertStore(signerConfig.certificates); X509Certificate signerCert = signerConfig.certificates.get(0); String jcaSignatureAlgorithm = getJcaSignatureAlgorithm( signerCert.getPublicKey(), signerConfig.signatureDigestAlgorithm); try { ContentSigner signer = new JcaContentSignerBuilder(jcaSignatureAlgorithm) .build(signerConfig.privateKey); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator( new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().build(), SignerInfoSignatureAlgorithmFinder.INSTANCE) .setDirectSignature(true) .build(signer, new JcaX509CertificateHolder(signerCert))); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(signatureFileBytes), false); ByteArrayOutputStream out = new ByteArrayOutputStream(); try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) { DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject()); } return out.toByteArray(); } catch (OperatorCreationException | CMSException | IOException e) { throw new SignatureException("Failed to generate signature", e); } }
/** * return the issuer of the given cert as an X509PrincipalObject. */ public static X509Principal getIssuerX509Principal( X509Certificate cert) throws CertificateEncodingException { try { TBSCertificateStructure tbsCert = TBSCertificateStructure.getInstance( ASN1Primitive.fromByteArray(cert.getTBSCertificate())); return new X509Principal(X509Name.getInstance(tbsCert.getIssuer())); } catch (IOException e) { throw new CertificateEncodingException(e.toString()); } }
@Override public String getSha1Fingerprint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException, IllegalArgumentException { if(cert == null) { throw new IllegalArgumentException("Provided certificate is empty"); } MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = cert.getEncoded(); md.update(der); byte[] digest = md.digest(); return DatatypeConverter.printHexBinary(digest); }
private void writeCertArray(Writer writer, Certificate[] certificates) throws IOException { if (certificates == null) { writer.write("-1\n"); return; } try { writer.write(Integer.toString(certificates.length) + '\n'); for (Certificate certificate : certificates) { byte[] bytes = certificate.getEncoded(); String line = Base64.encode(bytes); writer.write(line + '\n'); } } catch (CertificateEncodingException e) { throw new IOException(e.getMessage()); } }
/** Process the value of {@link X509Credential#getEntityCertificateChain()}. * * @param keyInfo the KeyInfo that is being built * @param x509Data the X509Data that is being built * @param credential the Credential that is being processed * @throws SecurityException thrown if the certificate data can not be encoded from the Java certificate object */ protected void processEntityCertificateChain(KeyInfo keyInfo, X509Data x509Data, X509Credential credential) throws SecurityException { if (options.emitEntityCertificateChain && credential.getEntityCertificateChain() != null) { for (java.security.cert.X509Certificate javaCert : credential.getEntityCertificateChain()) { try { X509Certificate xmlCert = KeyInfoHelper.buildX509Certificate(javaCert); x509Data.getX509Certificates().add(xmlCert); } catch (CertificateEncodingException e) { throw new SecurityException("Error generating X509Certificate element " + "from a certificate in credential's certificate chain", e); } } } }
@Override protected void onHandleIntent(Intent intent) { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LOWEST); if (intent == null || !ACTION_PARSE_APP.equals(intent.getAction())) { Utils.debugLog(TAG, "received bad Intent: " + intent); return; } try { PackageManager pm = getPackageManager(); String packageName = intent.getData().getSchemeSpecificPart(); App app = new App(this, pm, packageName); SwapService.putAppInCache(packageName, app); } catch (CertificateEncodingException | IOException | PackageManager.NameNotFoundException e) { e.printStackTrace(); } }
/** * Returns the private key signature on JBMR2+ or else null. */ public static String getSigningKey(String alias) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Certificate cert = getPrivateKeyEntry(alias).getCertificate(); if (cert == null) { return null; } try { return Base64.encodeToString(cert.getEncoded(), Base64.NO_WRAP); } catch (CertificateEncodingException e) { e.printStackTrace(); return null; } } else { return null; } }
/** * return the subject of the given cert as an X509PrincipalObject. */ public static X509Principal getSubjectX509Principal( X509Certificate cert) throws CertificateEncodingException { try { ByteArrayInputStream bIn = new ByteArrayInputStream( cert.getTBSCertificate()); ASN1InputStream aIn = new ASN1InputStream(bIn); TBSCertificateStructure tbsCert = new TBSCertificateStructure( (ASN1Sequence)aIn.readObject()); return new X509Principal(tbsCert.getSubject()); } catch (IOException e) { throw new CertificateEncodingException(e.toString()); } }
private int calculateHashCode() { try { int hashCode = 0; byte[] certData = this.getEncoded(); for (int i = 1; i < certData.length; i++) { hashCode += certData[i] * i; } return hashCode; } catch (CertificateEncodingException e) { return 0; } }
/** * Extract the private key a client certificate from a X509 certificate and write them to disk. * * @param certificatCredential Jenkins certificateCredential * @param clientCrtFile path where to write of the certificate * @param clientKeyFile path where to write of the private key * @throws IOException lol * @throws InterruptedException on file operation */ public static void extractFromCertificate(StandardCertificateCredentials certificatCredential, FilePath clientCrtFile, FilePath clientKeyFile) throws IOException, InterruptedException { try { KeyStore keyStore = certificatCredential.getKeyStore(); String alias = keyStore.aliases().nextElement(); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); // Get private key using passphrase Key key = keyStore.getKey(alias, Secret.toString(certificatCredential.getPassword()).toCharArray()); // Write certificate String encodedClientCrt = wrapCertificate(Base64.encodeBase64String(certificate.getEncoded())); clientCrtFile.write(encodedClientCrt, null); // Write private key String encodedClientKey = wrapPrivateKey(Base64.encodeBase64String(key.getEncoded())); clientKeyFile.write(encodedClientKey, null); } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateEncodingException e) { throw new AbortException(e.getMessage()); } }
private void encodeCertificate( Certificate cert, DataOutputStream dOut) throws IOException { try { byte[] cEnc = cert.getEncoded(); dOut.writeUTF(cert.getType()); dOut.writeInt(cEnc.length); dOut.write(cEnc); } catch (CertificateEncodingException ex) { throw new IOException(ex.toString()); } }
/** * Gets the requested finger print of the certificate. */ private static String getCertificateFingerPrint(String mdAlg, X509Certificate cert) { String fingerPrint = ""; try { byte[] encCertInfo = cert.getEncoded(); MessageDigest md = MessageDigest.getInstance(mdAlg); byte[] digest = md.digest(encCertInfo); StringBuffer buf = new StringBuffer(); for (int i = 0; i < digest.length; i++) { byte2hex(digest[i], buf); } fingerPrint = buf.toString(); } catch (NoSuchAlgorithmException | CertificateEncodingException e) { // ignored } return fingerPrint; }
@Test public void test() { byte[] encoded = MathUtils.toByteArray(1, 100); String base64Pin = BaseEncodingUtils.encodeBase64ToString(digester.digest(encoded)); MockX509Certificate cert = new MockX509Certificate(encoded); CertificatePin pin = new CertificatePin(base64Pin, digester); try { boolean result = pin.verify(cert); Assert.assertTrue(result); } catch (CertificateEncodingException ex) { Assert.fail(ex.getMessage()); } }
/** * Create a self-signed X.509 Certificate. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate */ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException { Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000l); BigInteger sn = new BigInteger(64, new SecureRandom()); KeyPair keyPair = pair; X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal dnName = new X500Principal(dn); certGen.setSerialNumber(sn); certGen.setIssuerDN(dnName); certGen.setNotBefore(from); certGen.setNotAfter(to); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(algorithm); X509Certificate cert = certGen.generate(pair.getPrivate()); return cert; }
/** * Signs the provided APK using JAR signing (aka v1 signature scheme) and returns the list of * JAR entries which need to be added to the APK as part of the signature. * * @param signerConfigs signer configurations, one for each signer. At least one signer config * must be provided. * * @throws InvalidKeyException if a signing key is not suitable for this signature scheme or * cannot be used in general * @throws SignatureException if an error occurs when computing digests of generating * signatures */ public static List<Pair<String, byte[]>> sign( List<SignerConfig> signerConfigs, DigestAlgorithm jarEntryDigestAlgorithm, Map<String, byte[]> jarEntryDigests, List<Integer> apkSigningSchemeIds, byte[] sourceManifestBytes) throws InvalidKeyException, CertificateEncodingException, SignatureException { if (signerConfigs.isEmpty()) { throw new IllegalArgumentException("At least one signer config must be provided"); } OutputManifestFile manifest = generateManifestFile(jarEntryDigestAlgorithm, jarEntryDigests, sourceManifestBytes); return signManifest(signerConfigs, jarEntryDigestAlgorithm, apkSigningSchemeIds, manifest); }
private ArrayList<CertificateBasicInfoModel> getCertificateBasicInfoModelList() { ArrayList<CertificateBasicInfoModel> certificateBasicInfoModels = new ArrayList<>(); for (CertificateResolverModel basicInfoModel : this.certificateResolverModels) { try { certificateBasicInfoModels.add(new CertificateBasicInfoModel( basicInfoModel.getAlias(), this.trustManager.getSha1Fingerprint(basicInfoModel.getCertificate()), basicInfoModel.getCertificate().getIssuerDN().getName(), basicInfoModel.getCertificate().getNotBefore(), basicInfoModel.getCertificate().getNotAfter(), basicInfoModel.getCertificate().getSigAlgName(), this.trustManager.certificateToString(basicInfoModel.getCertificate())) ); } catch (NoSuchAlgorithmException | CertificateEncodingException e) { log.error("Cannot create certificate basic information model", e); } } return certificateBasicInfoModels; }
/** * Returns the intermediate certificates (sub CAs) from a given certificate chain. * * @param certChain The certificate chain given as an array of Certificate instances * @return The sub certificates given as a list of byte arrays contained in a SubCertiticatesType instance */ public static SubCertificatesType getSubCertificates(Certificate[] certChain) { SubCertificatesType subCertificates = new SubCertificatesType(); for (Certificate cert : certChain) { X509Certificate x509Cert = (X509Certificate) cert; // Check whether the pathLen constraint is set which indicates if this certificate is a CA if (x509Cert.getBasicConstraints() != -1) try { subCertificates.getCertificate().add(x509Cert.getEncoded()); } catch (CertificateEncodingException e) { X500Principal subject = x509Cert.getIssuerX500Principal(); getLogger().error("A CertificateEncodingException occurred while trying to get certificate " + "with distinguished name '" + subject.getName().toString() + "'", e); } } if (subCertificates.getCertificate().size() == 0) { getLogger().warn("No intermediate CAs found in given certificate array"); } return subCertificates; }
private boolean isPinned(X509Certificate cert) throws CertificateEncodingException { for (Pin pin : this.pins) { if (pin.verify(cert)) { return true; } } return false; }
private void writeCertList(BufferedSink sink, List<Certificate> certificates) throws IOException { try { sink.writeDecimalLong(certificates.size()) .writeByte('\n'); for (int i = 0, size = certificates.size(); i < size; i++) { byte[] bytes = certificates.get(i).getEncoded(); String line = ByteString.of(bytes).base64(); sink.writeUtf8(line) .writeByte('\n'); } } catch (CertificateEncodingException e) { throw new IOException(e.getMessage()); } }
private PrivateKey resolveX509Certificate( XMLX509Certificate x509Cert ) throws XMLSecurityException, KeyStoreException { log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?"); byte[] x509CertBytes = x509Cert.getCertificateBytes(); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isKeyEntry(alias)) { Certificate cert = keyStore.getCertificate(alias); if (cert instanceof X509Certificate) { byte[] certBytes = null; try { certBytes = cert.getEncoded(); } catch (CertificateEncodingException e1) { } if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) { log.log(java.util.logging.Level.FINE, "match !!! "); try { Key key = keyStore.getKey(alias, password); if (key instanceof PrivateKey) { return (PrivateKey) key; } } catch (Exception e) { log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); // Keep searching } } } } } return null; }
/** * Encode the CertPath using PKCS#7 format. * * @return a byte array containing the binary encoding of the PKCS#7 object * @exception CertificateEncodingException if an exception occurs */ private byte[] encodePKCS7() throws CertificateEncodingException { PKCS7 p7 = new PKCS7(new AlgorithmId[0], new ContentInfo(ContentInfo.DATA_OID, null), certs.toArray(new X509Certificate[certs.size()]), new SignerInfo[0]); DerOutputStream derout = new DerOutputStream(); try { p7.encodeSignedData(derout); } catch (IOException ioe) { throw new CertificateEncodingException(ioe.getMessage()); } return derout.toByteArray(); }
byte[] getCertificateBytes(){ try { return this.certificate.getEncoded(); } catch (CertificateEncodingException e){ Log.e("Server", "getCertificateBytes"); Log.e("StackTrace", Log.getStackTraceString(e)); return null; } }
public CertificateFile(X509Certificate cert, String realmString, int failures, boolean temporarily) throws CertificateEncodingException { super(getNBCertFile(realmString)); setCert(cert); setFailures(failures); setRealmString(realmString); if(temporarily) { getFile().deleteOnExit(); } }
public static String w(Context context) { PackageInfo packageInfo; String str = null; try { packageInfo = context.getPackageManager().getPackageInfo(v(context), 64); } catch (NameNotFoundException e) { e.printStackTrace(); Object obj = str; } InputStream byteArrayInputStream = new ByteArrayInputStream(packageInfo.signatures[0].toByteArray()); try { CertificateFactory instance = CertificateFactory.getInstance("X509"); } catch (CertificateException e2) { e2.printStackTrace(); obj = str; } try { X509Certificate x509Certificate = (X509Certificate) instance.generateCertificate(byteArrayInputStream); } catch (CertificateException e22) { e22.printStackTrace(); obj = str; } try { str = a(MessageDigest.getInstance(Coder.KEY_MD5).digest(x509Certificate.getEncoded())); } catch (NoSuchAlgorithmException e3) { e3.printStackTrace(); } catch (CertificateEncodingException e4) { e4.printStackTrace(); } return str; }
public static String hex(Certificate cert) { byte[] encoded; try { encoded = cert.getEncoded(); } catch (CertificateEncodingException e) { encoded = new byte[0]; } return hex(encoded); }
/** * Return the DER encoded form of the certificate pair. * * @return The encoded form of the certificate pair. * @throws CerticateEncodingException If an encoding exception occurs. */ public byte[] getEncoded() throws CertificateEncodingException { try { if (encoded == null) { DerOutputStream tmp = new DerOutputStream(); emit(tmp); encoded = tmp.toByteArray(); } } catch (IOException ex) { throw new CertificateEncodingException(ex.toString()); } return encoded; }
/** * generate an X509 certificate, based on the current issuer and subject, * using the passed in provider for the signing, and the passed in source * of randomness (if required). */ public X509Certificate generate( PrivateKey key, String provider) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { return generate(key, provider, null); }
/** * Builds an {@link org.opensaml.xml.signature.X509Certificate} XMLObject from a native * Java {@link java.security.cert.X509Certificate}. * * @param cert the Java {@link java.security.cert.X509Certificate} to convert * @return a {@link org.opensaml.xml.signature.X509Certificate} XMLObject * @throws CertificateEncodingException thrown when there is an error converting the Java * certificate representation to the XMLObject representation */ public static org.opensaml.xml.signature.X509Certificate buildX509Certificate(X509Certificate cert) throws CertificateEncodingException { org.opensaml.xml.signature.X509Certificate xmlCert = (org.opensaml.xml.signature.X509Certificate) Configuration.getBuilderFactory() .getBuilder(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME) .buildObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME); xmlCert.setValue(Base64.encodeBytes(cert.getEncoded())); return xmlCert; }
/** * Encode the CertPath using PKIPATH format. * * @return a byte array containing the binary encoding of the PkiPath object * @exception CertificateEncodingException if an exception occurs */ private byte[] encodePKIPATH() throws CertificateEncodingException { ListIterator<X509Certificate> li = certs.listIterator(certs.size()); try { DerOutputStream bytes = new DerOutputStream(); // encode certs in reverse order (trust anchor to target) // according to PkiPath format while (li.hasPrevious()) { X509Certificate cert = li.previous(); // check for duplicate cert if (certs.lastIndexOf(cert) != certs.indexOf(cert)) { throw new CertificateEncodingException ("Duplicate Certificate"); } // get encoded certificates byte[] encoded = cert.getEncoded(); bytes.write(encoded); } // Wrap the data in a SEQUENCE DerOutputStream derout = new DerOutputStream(); derout.write(DerValue.tag_SequenceOf, bytes); return derout.toByteArray(); } catch (IOException ioe) { throw new CertificateEncodingException("IOException encoding " + "PkiPath data: " + ioe, ioe); } }
/** * generate an X509 certificate, based on the current issuer and subject, * using the passed in provider for the signing. */ public X509Certificate generate( PrivateKey key, String provider) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { return generate(key, provider, null); }
/** * generate an X509 certificate, based on the current issuer and subject, * using the passed in provider for the signing and the supplied source * of randomness, if required. */ public X509AttributeCertificate generate( PrivateKey key, String provider, SecureRandom random) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { if (!extGenerator.isEmpty()) { acInfoGen.setExtensions(extGenerator.generate()); } AttributeCertificateInfo acInfo = acInfoGen.generateAttributeCertificateInfo(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(acInfo); v.add(sigAlgId); try { v.add(new DERBitString(X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, acInfo))); return new X509V2AttributeCertificate(new AttributeCertificate(new DERSequence(v))); } catch (IOException e) { throw new ExtCertificateEncodingException("constructed invalid certificate", e); } }
private static List<byte[]> encodeCertificates(List<X509Certificate> certificates) throws CertificateEncodingException { List<byte[]> result = new ArrayList<>(certificates.size()); for (X509Certificate certificate : certificates) { result.add(certificate.getEncoded()); } return result; }
/** * Add a given extension field for the standard extensions tag (tag 3) * copying the extension value from another certificate. * * @param oid the type of the extension to be copied. * @param critical true if the extension is to be marked critical, false otherwise. * @param certificate the source of the extension to be copied. * @return the builder instance. */ public JcaX509v3CertificateBuilder copyAndAddExtension( ASN1ObjectIdentifier oid, boolean critical, X509Certificate certificate) throws CertificateEncodingException { this.copyAndAddExtension(oid, critical, new JcaX509CertificateHolder(certificate)); return this; }
public byte[] getEncoded() throws CertificateEncodingException { try { return c.getEncoded(ASN1Encoding.DER); } catch (IOException e) { throw new CertificateEncodingException(e.toString()); } }
private static Certificate convertCert(X509Certificate certificate) throws IOException { try { return Certificate.getInstance(certificate.getEncoded()); } catch (CertificateEncodingException e) { throw new PKCSIOException("cannot encode certificate: " + e.getMessage(), e); } }
public byte[] getTBSCertificate() throws CertificateEncodingException { try { return c.getTBSCertificate().getEncoded(ASN1Encoding.DER); } catch (IOException e) { throw new CertificateEncodingException(e.toString()); } }
public boolean equals( Object o) { if (o == this) { return true; } if (!(o instanceof Certificate)) { return false; } Certificate other = (Certificate)o; try { byte[] b1 = this.getEncoded(); byte[] b2 = other.getEncoded(); return Arrays.areEqual(b1, b2); } catch (CertificateEncodingException e) { return false; } }
/** * Return a DERObject containing the encoded certificate. * * @param cert the X509Certificate object to be encoded * * @return the DERObject **/ private ASN1Primitive toASN1Object( X509Certificate cert) throws CertificateEncodingException { try { return new ASN1InputStream(cert.getEncoded()).readObject(); } catch (Exception e) { throw new CertificateEncodingException("Exception while encoding certificate: " + e.toString()); } }