List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber
public void setSerialNumber(BigInteger serialNumber)
From source file:net.java.bd.tools.security.SecurityUtil.java
License:Open Source License
void issueCert(String csrfile, String certfile, String alias, String keypass) throws Exception { PKCS10CertificationRequest csr = new PKCS10CertificationRequest(convertFromBASE64(csrfile)); String subject = csr.getCertificationRequestInfo().getSubject().toString(); // Generate the app certificate X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.reset();/*from w w w .ja va 2 s . co m*/ X509Certificate rootCert = (X509Certificate) store.getCertificate(alias); if (rootCert == null) { System.out .println("ERROR: Aborting application certificate creation." + " No root certificate to sign."); cleanup(); // removes the self signed certificate from the keystore System.exit(1); } cg.setIssuerDN(new X509Name(true, rootCert.getSubjectDN().getName(), new X509BDJEntryConverter())); cg.setSubjectDN(new X509Name(subject, new X509BDJEntryConverter())); cg.setNotBefore(rootCert.getNotBefore()); cg.setNotAfter(rootCert.getNotAfter()); cg.setPublicKey(csr.getPublicKey()); cg.setSerialNumber(appCertSerNo); // BD-J mandates using SHA1WithRSA as a signature Algorithm cg.setSignatureAlgorithm("SHA1WITHRSA"); cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature)); // FIXME: Ideally this should be pulled out from the original app cert's // extension. Email on X500Name is not encoded with UTF8String. cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName)); // Assuming that the root certificate was generated using our tool, // the certificate should have IssuerAlternativeNames as an extension. if (rootCert.getIssuerAlternativeNames() == null) { System.out.println("ERROR: the root certificate must have an alternate name"); System.exit(1); } List issuerName = (List) rootCert.getIssuerAlternativeNames().iterator().next(); cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name((String) issuerName.get(1))); PrivateKey privateKey = (PrivateKey) store.getKey(alias, keypass.toCharArray()); X509Certificate cert = cg.generate(privateKey); // Now, write leaf certificate System.out.println("Writing cert to " + certfile + "."); FileOutputStream str = new FileOutputStream(certfile); str.write(cert.getEncoded()); str.close(); }
From source file:net.jmhertlein.core.crypto.Certs.java
License:Open Source License
/** * Generates an X509 certificate//from www . ja v a2 s. c o m * * Valid for 1000 years from 1 second ago, signed with SHA512withECDSA * @param authorityPrivateKey private key of the certificate authority * @param certPubKey pubkey that the certificate will use * @param serialNumber serial number of the certificate * @param commonName common name of the subject of this certificate * @return a new X509 Certificate * @throws SignatureException * @throws InvalidKeyException */ public static Certificate newCertificate(PrivateKey authorityPrivateKey, PublicKey certPubKey, long serialNumber, String commonName) throws SignatureException, InvalidKeyException { X509V3CertificateGenerator gen = new X509V3CertificateGenerator(); gen.setPublicKey(certPubKey); //pubkey of cert we're making gen.setSignatureAlgorithm("SHA512withECDSA"); gen.setSerialNumber(BigInteger.valueOf(Math.abs(serialNumber))); gen.setIssuerDN(new X500Principal("CN=" + commonName)); gen.setNotBefore(new Date(System.currentTimeMillis() - 1000L)); gen.setNotAfter(new Date(System.currentTimeMillis() + 1000 * 365 * 24 * 60 * 60 * 1000)); //tfw cert valid for 10x longer than I'll be alive gen.setSubjectDN(new X500Principal("CN=" + commonName)); try { return gen.generate(authorityPrivateKey); //ca's private key } catch (CertificateEncodingException | IllegalStateException | NoSuchAlgorithmException ex) { Logger.getLogger(Certs.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:net.jxta.impl.membership.pse.PSEUtils.java
License:Open Source License
/** * Generate a Cert given a keypair//from w ww .j ava 2s .co m * * @param subject subjectDN for the certificate * @param keypair the keypair to use. * @param issuerinfo the cert issuer or null if self-signed root cert. * @return the details of the generated cert. * @throws SecurityException if the cert could not be generated. */ public static IssuerInfo genCert(X500Principal subject, KeyPair keypair, IssuerInfo issuerinfo) throws SecurityException { try { // set up issuer PrivateKey signer; X509Principal issuer; if (null == issuerinfo) { // self-signed root cert signer = keypair.getPrivate(); issuer = new X509Principal(subject.getEncoded()); } else { // issuer signed service sert signer = issuerinfo.subjectPkey; X500Principal issuer_subject = issuerinfo.cert.getSubjectX500Principal(); issuer = new X509Principal(issuer_subject.getEncoded()); } // set validity 10 years from today Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(today); cal.add(Calendar.YEAR, 10); Date until = cal.getTime(); // generate cert X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(issuer); certGen.setSubjectDN(new X509Principal(subject.getEncoded())); certGen.setNotBefore(today); certGen.setNotAfter(until); certGen.setPublicKey(keypair.getPublic()); // certGen.setSignatureAlgorithm("SHA1withDSA"); certGen.setSignatureAlgorithm("SHA1WITHRSA"); // FIXME bondolo 20040317 needs fixing. certGen.setSerialNumber(BigInteger.valueOf(1)); // return issuer info for generating service cert IssuerInfo info = new IssuerInfo(); // the cert info.cert = certGen.generateX509Certificate(signer, UTILS.srng); // For saving service cert private key info.subjectPkey = keypair.getPrivate(); // for signing service cert info.issuer = (null == issuerinfo) ? info.cert : issuerinfo.cert; // for signing service cert info.issuerPkey = signer; // dump the certificate? if (null == issuer) { Logging.logCheckedFine(LOG, "Root Cert : \n", info.cert); } else { Logging.logCheckedFine(LOG, "Client Cert : \n", info.cert); } return info; } catch (SignatureException e) { Logging.logCheckedSevere(LOG, "Could not generate certificate\n\n", e); SecurityException failure = new SecurityException("Could not generate certificate"); failure.initCause(e); throw failure; } catch (InvalidKeyException e) { Logging.logCheckedSevere(LOG, "Could not generate certificate\n\n", e); SecurityException failure = new SecurityException("Could not generate certificate"); failure.initCause(e); throw failure; } catch (IOException e) { Logging.logCheckedSevere(LOG, "Could not generate certificate\n\n", e); SecurityException failure = new SecurityException("Could not generate certificate"); failure.initCause(e); throw failure; } }
From source file:net.laubenberger.bogatyr.service.crypto.CertificateProviderImpl.java
License:Open Source License
@Override public X509Certificate generateCertificate(final KeyPair pair, final String issuerDN, final String subjectDN, final String generalName, final Date start, final Date end) throws NoSuchAlgorithmException, IllegalStateException, CertificateEncodingException, InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException { //$JUnit$ if (null == pair) { throw new RuntimeExceptionIsNull("pair"); //$NON-NLS-1$ }/*from ww w. j a v a 2 s . c o m*/ if (null == issuerDN) { throw new RuntimeExceptionIsNull("issuerDN"); //$NON-NLS-1$ } if (!HelperString.isValid(issuerDN)) { throw new RuntimeExceptionIsEmpty("issuerDN"); //$NON-NLS-1$ } if (null == subjectDN) { throw new RuntimeExceptionIsNull("subjectDN"); //$NON-NLS-1$ } if (!HelperString.isValid(subjectDN)) { throw new RuntimeExceptionIsEmpty("subjectDN"); //$NON-NLS-1$ } if (null == generalName) { throw new RuntimeExceptionIsNull("generalName"); //$NON-NLS-1$ } if (!HelperString.isValid(generalName)) { throw new RuntimeExceptionIsEmpty("generalName"); //$NON-NLS-1$ } if (null == start) { throw new RuntimeExceptionIsNull("start"); //$NON-NLS-1$ } if (null == end) { throw new RuntimeExceptionIsNull("end"); //$NON-NLS-1$ } if (start.after(end)) { throw new RuntimeExceptionMustBeBefore("start", start, end); //$NON-NLS-1$ } // generate the certificate final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal(issuerDN)); certGen.setNotBefore(start); certGen.setNotAfter(end); certGen.setSubjectDN(new X500Principal(subjectDN)); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //$NON-NLS-1$ 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)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, generalName))); return certGen.generate(pair.getPrivate(), provider.getName()); }
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./* w w w. ja v a 2 s.co 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 w ww . j a va 2s . 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; }
From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java
License:Open Source License
/** * Creates a typical Certification Authority (CA) certificate. * @param keyPair/*www.j a v a 2 s .c om*/ * @throws SecurityException * @throws InvalidKeyException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ @SuppressWarnings("deprecation") public static X509Certificate createTypicalMasterCert(final KeyPair keyPair) throws SignatureException, InvalidKeyException, SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); X509Principal issuer = new X509Principal( "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US"); // Create v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(issuer); v3CertGen.setSubjectDN(issuer); //Set validity period v3CertGen .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30))); v3CertGen .setNotAfter(new Date(System.currentTimeMillis() + 240 /* months */ * (1000L * 60 * 60 * 24 * 30))); //Set signature algorithm & public key v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // Add typical extensions for signing cert v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); v3CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector(); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth)); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning)); typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown)); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages)); X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC"); cert.checkValidity(new Date()); cert.verify(keyPair.getPublic()); return cert; }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
License:Open Source License
/** * Generate an X509 cert for use as the keystore cert chain * //from w ww . j av a 2 s.c o m * @param keyPair * @return */ private X509Certificate generateCertificate(KeyPair keyPair, NodeRef person) { X509Certificate cert = null; int validDuration = Integer .parseInt(config.getProperty(RepositoryManagedSignatureProviderFactory.VALID_DURATION)); // get user's first and last name Map<QName, Serializable> props = serviceRegistry.getNodeService().getProperties(person); String firstName = String.valueOf(props.get(ContentModel.PROP_FIRSTNAME)); String lastName = String.valueOf(props.get(ContentModel.PROP_LASTNAME)); // backdate the start date by a day Calendar start = Calendar.getInstance(); start.add(Calendar.DATE, -1); java.util.Date startDate = start.getTime(); // what is the end date for this cert's validity? Calendar end = Calendar.getInstance(); end.add(Calendar.DATE, validDuration); java.util.Date endDate = end.getTime(); try { // This code works with newer versions of the BouncyCastle libraries, but not // the (severely outdated) version that ships with Alfresco /*X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder( new X500Principal("CN=" + firstName + " " + lastName), BigInteger.ONE, startDate, cal.getTime(), new X500Principal("CN=" + firstName + " " + lastName), keyPair.getPublic()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter keyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(keyParam); X509CertificateHolder certHolder = certBuilder.build(sigGen); // now lets convert this thing back to a regular old java cert CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certIs = new ByteArrayInputStream(certHolder.getEncoded()); cert = (X509Certificate) cf.generateCertificate(certIs); certIs.close();*/ X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal subjectName = new X500Principal("CN=" + firstName + " " + lastName); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setNotBefore(startDate); certGen.setNotAfter(endDate); certGen.setSubjectDN(subjectName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // if we are actually generating a trusted cert, the action is a little different boolean generateTrusted = Boolean.parseBoolean( config.getProperty(RepositoryManagedSignatureProviderFactory.ENABLE_TRUSTED_CERTS)); if (generateTrusted) { KeyStore trustedKs = getTrustedKeyStore(); PrivateKey caKey = getCaKey(trustedKs); X509Certificate caCert = getCaCert(trustedKs); // set the issuer of the generated cert to the subject of the ca cert X500Principal caSubject = caCert.getSubjectX500Principal(); certGen.setIssuerDN(caSubject); //add the required extensions for the new cert certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); cert = certGen.generate(caKey, "BC"); //verify the cert cert.verify(caCert.getPublicKey()); } else { certGen.setIssuerDN(subjectName); cert = certGen.generate(keyPair.getPrivate(), "BC"); } } catch (CertificateException ce) { logger.error("CertificateException creating or validating X509 certificate for user: " + ce); throw new AlfrescoRuntimeException(ce.getMessage()); } catch (Exception ex) { logger.error("Unknown exception creating or validating X509 certificate for user : " + ex); ex.printStackTrace(); } return cert; }
From source file:org.apache.brooklyn.util.core.crypto.FluentKeySigner.java
License:Apache License
@SuppressWarnings("deprecation") public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify) { try {// w w w.j a v a2s . c o m org.bouncycastle.x509.X509V3CertificateGenerator v3CertGen = new org.bouncycastle.x509.X509V3CertificateGenerator(); v3CertGen.setSerialNumber(serialNumber != null ? serialNumber : // must be positive BigInteger.valueOf(srand.nextLong()).abs().add(BigInteger.ONE)); v3CertGen.setIssuerDN(issuerPrincipal); v3CertGen.setNotBefore(validityStartDate); v3CertGen.setNotAfter(validityEndDate); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); v3CertGen.setSubjectDN(subject); v3CertGen.setPublicKey(keyToCertify); v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false, new org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure(keyToCertify)); if (authorityKeyIdentifier != null) v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); X509Certificate pkCertificate = v3CertGen.generate(issuerKey.getPrivate(), "BC"); return pkCertificate; } catch (Exception e) { throw Exceptions.propagate(e); } }
From source file:org.apache.kerby.pkix.EndEntityGenerator.java
License:Apache License
/** * Generate certificate./*w w w . ja v a2s . co m*/ * * @param issuerCert * @param issuerPrivateKey * @param publicKey * @param dn * @param validityDays * @param friendlyName * @return The certificate. * @throws InvalidKeyException * @throws SecurityException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws DataLengthException * @throws CertificateException */ public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey, PublicKey publicKey, String dn, int validityDays, String friendlyName) throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CertificateException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Set certificate attributes. certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert)); certGen.setSubjectDN(new X509Principal(dn)); certGen.setNotBefore(new Date()); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); certGen.setNotAfter(expiry.getTime()); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); // MAY set BasicConstraints=false or not at all. certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)); ASN1EncodableVector keyPurposeVector = new ASN1EncodableVector(); keyPurposeVector.add(KeyPurposeId.id_kp_smartcardlogon); //keyPurposeVector.add( KeyPurposeId.id_kp_serverAuth ); DERSequence keyPurposeOids = new DERSequence(keyPurposeVector); // If critical, will throw unsupported EKU. certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, keyPurposeOids); ASN1EncodableVector pkinitSanVector = new ASN1EncodableVector(); pkinitSanVector.add(ID_PKINIT_SAN); pkinitSanVector.add(new DERTaggedObject(0, new DERSequence())); DERSequence pkinitSan = new DERSequence(pkinitSanVector); String dnsName = "localhost"; GeneralName name1 = new GeneralName(GeneralName.otherName, pkinitSan); GeneralName name2 = new GeneralName(GeneralName.dNSName, dnsName); GeneralNamesBuilder genNamesBuilder = new GeneralNamesBuilder(); genNamesBuilder.addName(name1); genNamesBuilder.addName(name2); GeneralNames sanGeneralNames = genNamesBuilder.build(); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, sanGeneralNames); /* * The KDC MAY require the presence of an Extended Key Usage (EKU) KeyPurposeId * [RFC3280] id-pkinit-KPClientAuth in the extensions field of the client's * X.509 certificate. */ /* * The digitalSignature key usage bit [RFC3280] MUST be asserted when the * intended purpose of the client's X.509 certificate is restricted with * the id-pkinit-KPClientAuth EKU. */ /* * KDCs implementing this requirement SHOULD also accept the EKU KeyPurposeId * id-ms-kp-sc-logon (1.3.6.1.4.1.311.20.2.2) as meeting the requirement, as * there are a large number of X.509 client certificates deployed for use * with PKINIT that have this EKU. */ // KDC /* * In addition, unless the client can otherwise verify that the public key * used to verify the KDC's signature is bound to the KDC of the target realm, * the KDC's X.509 certificate MUST contain a Subject Alternative Name extension * [RFC3280] carrying an AnotherName whose type-id is id-pkinit-san (as defined * in Section 3.2.2) and whose value is a KRB5PrincipalName that matches the * name of the TGS of the target realm (as defined in Section 7.3 of [RFC4120]). */ /* * Unless the client knows by some other means that the KDC certificate is * intended for a Kerberos KDC, the client MUST require that the KDC certificate * contains the EKU KeyPurposeId [RFC3280] id-pkinit-KPKdc. */ /* * The digitalSignature key usage bit [RFC3280] MUST be asserted when the * intended purpose of the KDC's X.509 certificate is restricted with the * id-pkinit-KPKdc EKU. */ /* * If the KDC certificate contains the Kerberos TGS name encoded as an id-pkinit-san * SAN, this certificate is certified by the issuing CA as a KDC certificate, * therefore the id-pkinit-KPKdc EKU is not required. */ /* * KDC certificates issued by Windows 2000 Enterprise CAs contain a dNSName * SAN with the DNS name of the host running the KDC, and the id-kp-serverAuth * EKU [RFC3280]. */ /* * KDC certificates issued by Windows 2003 Enterprise CAs contain a dNSName * SAN with the DNS name of the host running the KDC, the id-kp-serverAuth * EKU, and the id-ms-kp-sc-logon EKU. */ /* * RFC: KDC certificates with id-pkinit-san SAN as specified in this RFC. * * MS: dNSName SAN containing the domain name of the KDC * id-pkinit-KPKdc EKU * id-kp-serverAuth EKU. */ /* * Client certificates accepted by Windows 2000 and Windows 2003 Server KDCs * must contain an id-ms-san-sc-logon-upn (1.3.6.1.4.1.311.20.2.3) SAN and * the id-ms-kp-sc-logon EKU. The id-ms-san-sc-logon-upn SAN contains a * UTF8-encoded string whose value is that of the Directory Service attribute * UserPrincipalName of the client account object, and the purpose of including * the id-ms-san-sc-logon-upn SAN in the client certificate is to validate * the client mapping (in other words, the client's public key is bound to * the account that has this UserPrincipalName value). */ X509Certificate cert = certGen.generate(issuerPrivateKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName)); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); return cert; }