List of usage examples for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier
ASN1ObjectIdentifier SubjectKeyIdentifier
To view the source code for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier.
Click Source Link
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
License:Open Source License
private X509V3CertificateGenerator buildX509V3CertificateGenerator(PublicKey publicKey, X509Certificate caCert, DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays) throws CertificateEncodingException, CertificateParsingException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // Calculate Expiration Date Calendar notBeforeCal = Calendar.getInstance(); Date notBeforeDate = notBeforeCal.getTime(); Calendar notAfterCal = Calendar.getInstance(); notAfterCal.add(Calendar.DAY_OF_YEAR, validDays); Date notAfterDate = notAfterCal.getTime(); ///*from w ww . j a va 2 s . co m*/ // create the certificate - version 3 // v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(serialNumber)); v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); v3CertGen.setNotBefore(notBeforeDate); v3CertGen.setNotAfter(notAfterDate); v3CertGen.setSubjectDN(new X509Principal(getAttributeOrder(), buildAttributes(distinguishedName))); v3CertGen.setPublicKey(publicKey); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // // extensions // v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); return v3CertGen; }
From source file:hu.akarnokd.utils.crypto.KeystoreManager.java
License:Apache License
/** * Generate a X509 certificate for the given keypair. * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode * use backslash to escape a comma//w ww . j a v a2s .co m * @param keypair the keypair * @param months the validity length in months * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param domain domain of the server to store in the subject alternative name extension * @param signAlgorithm the signing algorithm to use * @return the generated X509 certificate */ public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN, String domain, String signAlgorithm) { try { // calendar for date calculations GregorianCalendar cal = new GregorianCalendar(); // extract keypair components PublicKey pubKey = keypair.getPublic(); PrivateKey privKey = keypair.getPrivate(); // generate a random serial number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(System.currentTimeMillis()); byte[] serialNo = new byte[8]; random.nextBytes(serialNo); BigInteger serial = new BigInteger(serialNo).abs(); // create the certificate generator X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.reset(); // set certificate attributes certGen.setSerialNumber(serial); cal.setTimeInMillis(System.currentTimeMillis()); certGen.setNotBefore(cal.getTime()); cal.add(GregorianCalendar.MONTH, months); certGen.setNotAfter(cal.getTime()); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm(signAlgorithm); certGen.setIssuerDN(new X509Name(issuerDN)); certGen.setSubjectDN(new X509Name(subjectDN)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); // create subject alternative name boolean isCritical = subjectDN == null || "".equals(subjectDN.trim()); DERSequence othernameSeq = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERTaggedObject(true, 0, new DERUTF8String(domain)) }); GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq); GeneralNames subjectAlternatives = new GeneralNames(othernameGen); certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives); // finally generate the certificate X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(), new SecureRandom()); cert.checkValidity(new Date()); cert.verify(pubKey); return cert; } catch (NoSuchAlgorithmException ex) { throw new KeystoreFault(ex); } catch (CertificateException ex) { throw new KeystoreFault(ex); } catch (SignatureException ex) { throw new KeystoreFault(ex); } catch (NoSuchProviderException ex) { throw new KeystoreFault(ex); } catch (InvalidKeyException ex) { throw new KeystoreFault(ex); } }
From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java
License:Apache License
public static X509Certificate[] buildChain() throws Exception { // create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1);/*from w w w . j ava 2 s . c om*/ } // create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:io.aos.crypto.spl07.Utils.java
License:Apache License
/** * Generate a sample V3 certificate to use as an intermediate CA certificate *///from w ww .j av a2s .co m public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate")); certGen.setPublicKey(intKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); return certGen.generateX509Certificate(caKey, "BC"); }
From source file:io.aos.crypto.spl07.Utils.java
License:Apache License
/** * Generate a sample V3 certificate to use as an end entity certificate *///from w w w. j a v a 2 s .com public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test End Certificate")); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); return certGen.generateX509Certificate(caKey, "BC"); }
From source file:io.aos.crypto.spl08.CertReqSolution.java
License:Apache License
public static void main(String... args) throws Exception { // create the CA certificates X500PrivateCredential rootCredential = Utils.createRootCredential(); X500PrivateCredential interCredential = Utils.createIntermediateCredential(rootCredential.getPrivateKey(), rootCredential.getCertificate()); // parse the request PEMReader pRd = new PEMReader(new InputStreamReader(new FileInputStream("pkcs10.req"))); PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject(); // get our validation certificate X509Certificate caCert = interCredential.getCertificate(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // provide some basic extensions and mark the certificate as appropriate for signing and encipherment certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); // create the chain List chain = Arrays/* ww w. j a v a 2s .co m*/ .asList(new Certificate[] { certGen.generateX509Certificate(interCredential.getPrivateKey(), "BC"), interCredential.getCertificate(), rootCredential.getCertificate() }); // create the CertPath CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath path = fact.generateCertPath(chain); // write it out FileOutputStream fOut = new FileOutputStream("pkcs7.pth"); fOut.write(path.getEncoded("PKCS7")); fOut.close(); }
From source file:me.it_result.ca.bouncycastle.BouncyCABase.java
License:Open Source License
protected X509V3CertificateGenerator assembleCertificate(PublicKey publicKey, PublicKey caPublicKey, String subjectDN, String issuerDN, BigInteger serialNumber, boolean ca, int validityDays) throws CertificateParsingException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, FileNotFoundException { certGen.setIssuerDN(new X509Principal(issuerDN)); certGen.setNotBefore(new Date()); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.add(Calendar.DAY_OF_MONTH, validityDays); certGen.setNotAfter(cal.getTime());//from w w w . j a v a 2s .co m certGen.setPublicKey(publicKey); certGen.setSerialNumber(serialNumber); certGen.setSignatureAlgorithm(signatureAlgorithm); certGen.setSubjectDN(new X509Principal(subjectDN)); X509KeyUsage keyUsage; if (ca) keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign); else keyUsage = new X509KeyUsage(X509KeyUsage.keyEncipherment | X509KeyUsage.digitalSignature); certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage.getDEREncoded()); BasicConstraints basicConstraints = new BasicConstraints(ca); certGen.addExtension(X509Extensions.BasicConstraints, true, basicConstraints.getDEREncoded()); SubjectKeyIdentifierStructure subjectKeyId = new SubjectKeyIdentifierStructure(publicKey); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyId.getDEREncoded()); AuthorityKeyIdentifierStructure authorityKeyId = new AuthorityKeyIdentifierStructure(caPublicKey); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyId.getDEREncoded()); return certGen; }
From source file:me.it_result.ca.X509Assertions.java
License:Open Source License
public X509Assertions containsSKI() { assertNotNull(cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId())); nonCriticalExtension(X509Extensions.SubjectKeyIdentifier); return this; }
From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * Utility method for generating a "standard" server certificate. Recognized by most * browsers as valid for SSL/TLS. These certificates are generated de novo, not from * a template, so they will not retain the structure of the original certificate and may * not be suitable for applications that require Extended Validation/High Assurance SSL * or other distinct extensions or EKU./*from ww w .j a v a2 s .c o m*/ * * @param newPubKey * @param caCert * @param caPrivateKey * @param hostname * @return * @throws CertificateParsingException * @throws SignatureException * @throws InvalidKeyException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ @SuppressWarnings({ "deprecation", "unused" }) public static X509Certificate generateStdSSLServerCertificate(final PublicKey newPubKey, final X509Certificate caCert, final PrivateKey caPrivateKey, final String subject) throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSubjectDN(new X500Principal(subject)); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); v3CertGen.setPublicKey(newPubKey); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 30L * 60 * 60 * 24 * 30 * 12)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30 * 12)); v3CertGen.setIssuerDN(caCert.getSubjectX500Principal()); // Firefox actually tracks serial numbers within a CA and refuses to validate if it sees duplicates // This is not a secure serial number generator, (duh!) but it's good enough for our purposes. v3CertGen.setSerialNumber(new BigInteger(Long.toString(System.currentTimeMillis()))); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(newPubKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.getPublicKey())); // Firefox 2 disallows these extensions in an SSL server cert. IE7 doesn't care. // v3CertGen.addExtension( // X509Extensions.KeyUsage, // false, // new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature ) ); DEREncodableVector typicalSSLServerExtendedKeyUsages = new DEREncodableVector(); typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth)); typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.clientAuth)); typicalSSLServerExtendedKeyUsages .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.netscapeServerGatedCrypto)); typicalSSLServerExtendedKeyUsages .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.msServerGatedCrypto)); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalSSLServerExtendedKeyUsages)); // Disabled by default. Left in comments in case this is desired. // // v3CertGen.addExtension( // X509Extensions.AuthorityInfoAccess, // false, // new AuthorityInformationAccess(new DERObjectIdentifier(OID_ID_AD_CAISSUERS), // new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + subject + "/aia"))); // v3CertGen.addExtension( // X509Extensions.CRLDistributionPoints, // false, // new CRLDistPoint(new DistributionPoint[] {})); X509Certificate cert = v3CertGen.generate(caPrivateKey, "BC"); return cert; }
From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * This method creates an X509v3 certificate based on an an existing certificate. * It attempts to create as faithful a copy of the existing certificate as possible * by duplicating all certificate extensions. * * If you are testing an application that makes use of additional certificate * extensions (e.g. logotype, S/MIME capabilities) this method will preserve those * fields.//from ww w .j a v a 2 s . c o m * * You may optionally include a set of OIDs not to copy from the original certificate. * The most common reason to do this would be to remove fields that would cause inconsistency, * such as Authority Info Access or Issuer Alternative Name where these are not defined for * the MITM authority certificate. * * OIDs 2.5.29.14 : Subject Key Identifier and 2.5.29.35 : Authority Key Identifier, * are never copied, but generated directly based on the input keys and certificates. * * You may also optionally include maps of custom extensions which will be added to or replace * extensions with the same OID on the original certificate for the the MITM certificate. * * FUTURE WORK: JDK 1.5 is very strict in parsing extensions. In particular, known extensions * that include URIs must parse to valid URIs (including URL encoding all non-valid URI characters) * or the extension will be rejected and not available to copy to the MITM certificate. Will need * to directly extract these as ASN.1 fields and re-insert (hopefully BouncyCastle will handle them) * * * @param originalCert The original certificate to duplicate. * @param newPubKey The new public key for the MITM certificate. * @param caCert The certificate of the signing authority fot the MITM certificate. * @param caPrivateKey The private key of the signing authority. * @param extensionOidsNotToCopy An optional list of certificate extension OIDs not to copy to the MITM certificate. * @return The new MITM certificate. * @throws CertificateParsingException * @throws SignatureException * @throws InvalidKeyException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert, final PublicKey newPubKey, final X509Certificate caCert, final PrivateKey caPrivateKey, Set<String> extensionOidsNotToCopy) throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { if (extensionOidsNotToCopy == null) { extensionOidsNotToCopy = new HashSet<String>(); } X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSubjectDN(originalCert.getSubjectX500Principal()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // needs to be the same as the signing cert, not the copied cert v3CertGen.setPublicKey(newPubKey); v3CertGen.setNotAfter(originalCert.getNotAfter()); v3CertGen.setNotBefore(originalCert.getNotBefore()); v3CertGen.setIssuerDN(caCert.getSubjectX500Principal()); v3CertGen.setSerialNumber(originalCert.getSerialNumber()); // copy other extensions: Set<String> critExts = originalCert.getCriticalExtensionOIDs(); // get extensions returns null, not an empty set! if (critExts != null) { for (String oid : critExts) { if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)) { v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), true, originalCert); } } } Set<String> nonCritExs = originalCert.getNonCriticalExtensionOIDs(); if (nonCritExs != null) { for (String oid : nonCritExs) { if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)) { v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), false, originalCert); } } } v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(newPubKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.getPublicKey())); X509Certificate cert = v3CertGen.generate(caPrivateKey, "BC"); // For debugging purposes. //cert.checkValidity(new Date()); //cert.verify(caCert.getPublicKey()); return cert; }