Search in sources :

Example 16 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project nhin-d by DirectProject.

the class CertGenerator method createLeafCertificate.

private static CertCreateFields createLeafCertificate(CertCreateFields fields, KeyPair keyPair, boolean addAltNames) throws Exception {
    String altName = "";
    StringBuilder dnBuilder = new StringBuilder();
    // create the DN
    if (fields.getAttributes().containsKey("EMAILADDRESS")) {
        dnBuilder.append("EMAILADDRESS=").append(fields.getAttributes().get("EMAILADDRESS")).append(", ");
        altName = fields.getAttributes().get("EMAILADDRESS").toString();
    }
    if (fields.getAttributes().containsKey("CN"))
        dnBuilder.append("CN=").append(fields.getAttributes().get("CN")).append(", ");
    if (fields.getAttributes().containsKey("C"))
        dnBuilder.append("C=").append(fields.getAttributes().get("C")).append(", ");
    if (fields.getAttributes().containsKey("ST"))
        dnBuilder.append("ST=").append(fields.getAttributes().get("ST")).append(", ");
    if (fields.getAttributes().containsKey("L"))
        dnBuilder.append("L=").append(fields.getAttributes().get("L")).append(", ");
    if (fields.getAttributes().containsKey("O"))
        dnBuilder.append("O=").append(fields.getAttributes().get("O")).append(", ");
    String DN = dnBuilder.toString().trim();
    if (DN.endsWith(","))
        DN = DN.substring(0, DN.length() - 1);
    X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.DAY_OF_MONTH, fields.getExpDays());
    // not the best way to do this... generally done with a db file
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    // issuer is the parent cert
    v1CertGen.setIssuerDN(fields.getSignerCert().getSubjectX500Principal());
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    v1CertGen.setSubjectDN(new X509Principal(DN));
    v1CertGen.setPublicKey(keyPair.getPublic());
    v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
    // pointer to the parent CA
    v1CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(fields.getSignerCert()));
    v1CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
    boolean allowToSign = (fields.getAttributes().get("ALLOWTOSIGN") != null && fields.getAttributes().get("ALLOWTOSIGN").toString().equalsIgnoreCase("true"));
    v1CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(allowToSign));
    int keyUsage = 0;
    if (fields.getAttributes().get("KEYENC") != null && fields.getAttributes().get("KEYENC").toString().equalsIgnoreCase("true"))
        keyUsage = keyUsage | KeyUsage.keyEncipherment;
    if (fields.getAttributes().get("DIGSIG") != null && fields.getAttributes().get("DIGSIG").toString().equalsIgnoreCase("true"))
        keyUsage = keyUsage | KeyUsage.digitalSignature;
    if (keyUsage > 0)
        v1CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(keyUsage));
    if (fields.getSignerCert().getSubjectAlternativeNames() != null) {
        for (List<?> names : fields.getSignerCert().getSubjectAlternativeNames()) {
            GeneralNames issuerAltName = new GeneralNames(new GeneralName((Integer) names.get(0), names.get(1).toString()));
            v1CertGen.addExtension(X509Extensions.IssuerAlternativeName, false, issuerAltName);
        }
    }
    if (addAltNames && !altName.isEmpty()) {
        int nameType = altName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        GeneralNames subjectAltName = new GeneralNames(new GeneralName(nameType, altName));
        v1CertGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
    }
    // use the CA's private key to sign the certificate
    X509Certificate newCACert = v1CertGen.generate((PrivateKey) fields.getSignerKey(), CryptoExtensions.getJCEProviderName());
    // validate the certificate 
    newCACert.verify(fields.getSignerCert().getPublicKey());
    // write the certificate the file system
    writeCertAndKey(newCACert, keyPair.getPrivate(), fields);
    return fields;
}
Also used : SubjectKeyIdentifierStructure(org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure) Calendar(java.util.Calendar) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifierStructure(org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Principal(org.bouncycastle.jce.X509Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 17 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project nifi by apache.

the class CertificateUtils method generateIssuedCertificate.

/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 */
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));
        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // (3) subjectAlternativeName
        if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 18 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project Spark by igniterealtime.

the class IdentityController method createSelfSignedCertificate.

public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException {
    long serial = System.currentTimeMillis();
    SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X500Name name = new X500Name(createX500NameString());
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, BigInteger.valueOf(serial), new Date(System.currentTimeMillis() - 1000000000), new Date(System.currentTimeMillis() + 1000000000), name, keyInfo);
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = csBuilder.build(keyPair.getPrivate());
    X509CertificateHolder certHolder = certBuilder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
    return cert;
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 19 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project certmgr by hdecarne.

the class KeyUsageController method onApply.

@SuppressWarnings("unused")
private void onApply(ActionEvent evt) {
    boolean critical = this.ctlCritical.isSelected();
    Set<KeyUsage> usages = new HashSet<>();
    if (this.ctlAnyUsage.isSelected()) {
        usages.add(KeyUsage.ANY);
    } else {
        for (KeyUsage usage : this.ctlUsages.getSelectionModel().getSelectedItems()) {
            usages.add(usage);
        }
    }
    this.extensionDataResult = new KeyUsageExtensionData(critical, usages);
}
Also used : KeyUsageExtensionData(de.carne.certmgr.certs.x509.KeyUsageExtensionData) KeyUsage(de.carne.certmgr.certs.x509.KeyUsage) HashSet(java.util.HashSet)

Example 20 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project accumulo by apache.

the class CertUtils method generateCert.

private Certificate generateCert(KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, CertIOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException {
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.YEAR, 100);
    BigInteger serialNumber = BigInteger.valueOf((startDate.getTimeInMillis()));
    X500Name issuer = new X500Name(IETFUtils.rDNsFromString(issuerDirString, RFC4519Style.INSTANCE));
    JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic());
    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    certGen.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(isCertAuthority));
    certGen.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
    if (isCertAuthority) {
        certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
    }
    X509CertificateHolder cert = certGen.build(new JcaContentSignerBuilder(signingAlgorithm).build(signerPrivateKey));
    return new JcaX509CertificateConverter().getCertificate(cert);
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) Calendar(java.util.Calendar) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Aggregations

KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)22 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)14 Date (java.util.Date)12 X500Name (org.bouncycastle.asn1.x500.X500Name)12 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)12 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)12 X509Certificate (java.security.cert.X509Certificate)11 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)11 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)11 ContentSigner (org.bouncycastle.operator.ContentSigner)10 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)9 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)8 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)8 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)7 KeyPair (java.security.KeyPair)6 KeyStore (java.security.KeyStore)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 CertificateException (java.security.cert.CertificateException)6 IOException (java.io.IOException)5 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)5