Search in sources :

Example 16 with KeyUsage

use of com.google.cloud.security.privateca.v1.KeyUsage in project nifi by apache.

the class OcspCertificateValidatorTest method generateCertificate.

/**
 * Generates a signed certificate with a specific keypair.
 *
 * @param dn      the DN
 * @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateCertificate(String dn, KeyPair keyPair) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    PrivateKey privateKey = keyPair.getPrivate();
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(privateKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(dn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo);
    // Set certificate extensions
    // (1) digitalSignature extension
    certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement));
    // (2) extendedKeyUsage extension
    Vector<KeyPurposeId> ekUsages = new Vector<>();
    ekUsages.add(KeyPurposeId.id_kp_clientAuth);
    ekUsages.add(KeyPurposeId.id_kp_serverAuth);
    certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages));
    // Sign the certificate
    X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certificateHolder);
}
Also used : PrivateKey(java.security.PrivateKey) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) Vector(java.util.Vector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 17 with KeyUsage

use of com.google.cloud.security.privateca.v1.KeyUsage in project candlepin by candlepin.

the class BouncyCastlePKIUtility method createX509Certificate.

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {
    X509Certificate caCert = reader.getCACert();
    byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()), serialNumber, startDate, endDate, new X500Name(dn), SubjectPublicKeyInfo.getInstance(publicKeyEncoded));
    // set key usage - required for proper x509 function
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
    // add SSL extensions - required for proper x509 function
    NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, certType);
    certGen.addExtension(Extension.keyUsage, false, keyUsage);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    AuthorityKeyIdentifier aki = extensionUtil.createAuthorityKeyIdentifier(caCert);
    certGen.addExtension(Extension.authorityKeyIdentifier, false, aki.getEncoded());
    certGen.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
    certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    // Add an additional alternative name if provided.
    if (alternateName != null) {
        /*
             Why add the certificate subject again as an alternative name?  RFC 6125 Section 6.4.4
             stipulates that if SANs are provided, a validator MUST use them instead of the certificate
             subject.  If no SANs are present, the RFC allows the validator to use the subject field.  So,
             if we do have an SAN to add, we need to add the subject field again as an SAN.

             See http://stackoverflow.com/questions/5935369 and
             https://tools.ietf.org/html/rfc6125#section-6.4.4 and

             NB: These extensions should *not* be marked critical since the subject field is not empty.
            */
        GeneralName subject = new GeneralName(GeneralName.directoryName, dn);
        GeneralName name = new GeneralName(GeneralName.directoryName, "CN=" + alternateName);
        ASN1Encodable[] altNameArray = { subject, name };
        GeneralNames altNames = GeneralNames.getInstance(new DERSequence(altNameArray));
        certGen.addExtension(Extension.subjectAlternativeName, false, altNames);
    }
    if (extensions != null) {
        for (X509ExtensionWrapper wrapper : extensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            String value = wrapper.getValue() == null ? "" : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DERUTF8String(value));
        }
    }
    if (byteExtensions != null) {
        for (X509ByteExtensionWrapper wrapper : byteExtensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DEROctetString(value));
        }
    }
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNATURE_ALGO).setProvider(BC_PROVIDER);
    ContentSigner signer;
    try {
        signer = builder.build(reader.getCaKey());
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
    // Generate the certificate
    return new JcaX509CertificateConverter().getCertificate(certGen.build(signer));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERSequence(org.bouncycastle.asn1.DERSequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509ByteExtensionWrapper(org.candlepin.pki.X509ByteExtensionWrapper) X509ExtensionWrapper(org.candlepin.pki.X509ExtensionWrapper) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 18 with KeyUsage

use of com.google.cloud.security.privateca.v1.KeyUsage in project certmgr by hdecarne.

the class KeyUsageController method init.

/**
 * Initialize the dialog with existing extension data.
 *
 * @param data The extension data to use.
 * @param expertMode Whether to run in expert mode ({@code true}) or not ({@code false}).
 * @return This controller.
 */
public KeyUsageController init(KeyUsageExtensionData data, boolean expertMode) {
    init(expertMode);
    this.ctlCritical.setSelected(data.getCritical());
    if (data.hasUsage(KeyUsage.ANY)) {
        this.ctlAnyUsage.setSelected(true);
    } else {
        for (KeyUsage usage : data) {
            this.ctlUsages.getSelectionModel().select(usage);
        }
    }
    return this;
}
Also used : KeyUsage(de.carne.certmgr.certs.x509.KeyUsage)

Example 19 with KeyUsage

use of com.google.cloud.security.privateca.v1.KeyUsage in project certmgr by hdecarne.

the class KeyUsageController method init.

/**
 * Initialize the dialog.
 *
 * @param expertMode Whether to run in expert mode ({@code true}) or not ({@code false}).
 * @return This controller.
 */
public KeyUsageController init(boolean expertMode) {
    this.ctlCritical.setSelected(KeyUsageExtensionData.CRITICAL_DEFAULT);
    ObservableList<KeyUsage> usageItems = this.ctlUsages.getItems();
    for (KeyUsage usage : KeyUsage.instances()) {
        if (!KeyUsage.ANY.equals(usage)) {
            usageItems.add(usage);
        }
    }
    usageItems.sort((o1, o2) -> o1.name().compareTo(o2.name()));
    this.ctlUsages.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    this.ctlAnyUsage.setSelected(false);
    return this;
}
Also used : KeyUsage(de.carne.certmgr.certs.x509.KeyUsage)

Example 20 with KeyUsage

use of com.google.cloud.security.privateca.v1.KeyUsage in project pwm by pwm-project.

the class SelfCertGenerator method generateV3Certificate.

private X509Certificate generateV3Certificate(final KeyPair pair, final String cnValue) throws Exception {
    final X500NameBuilder subjectName = new X500NameBuilder(BCStyle.INSTANCE);
    subjectName.addRDN(BCStyle.CN, cnValue);
    final BigInteger serialNumber = makeSerialNumber();
    // 2 days in the past
    final Date notBefore = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2));
    final long futureSeconds = settings.getFutureSeconds();
    final Date notAfter = new Date(System.currentTimeMillis() + (futureSeconds * 1000));
    final X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(subjectName.build(), serialNumber, notBefore, notAfter, subjectName.build(), pair.getPublic());
    // false == not a CA
    final BasicConstraints basic = new BasicConstraints(false);
    // OID, critical, ASN.1 encoded value
    certGen.addExtension(Extension.basicConstraints, true, basic.getEncoded());
    // add subject alternate name
    {
        final ASN1Encodable[] subjectAlternativeNames = new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, cnValue) };
        final DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames);
        certGen.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);
    }
    // sign and key encipher
    final KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment);
    // OID, critical, ASN.1 encoded value
    certGen.addExtension(Extension.keyUsage, true, keyUsage.getEncoded());
    // server authentication
    final ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth);
    // OID, critical, ASN.1 encoded value
    certGen.addExtension(Extension.extendedKeyUsage, true, extKeyUsage.getEncoded());
    final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(pair.getPrivate());
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) Date(java.util.Date) DERSequence(org.bouncycastle.asn1.DERSequence) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Aggregations

KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)49 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)36 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)27 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)27 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)25 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)25 Date (java.util.Date)23 X500Name (org.bouncycastle.asn1.x500.X500Name)22 ContentSigner (org.bouncycastle.operator.ContentSigner)22 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)19 X509Certificate (java.security.cert.X509Certificate)18 BigInteger (java.math.BigInteger)14 GeneralName (org.bouncycastle.asn1.x509.GeneralName)14 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)14 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)14 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)14 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)11 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)11 KeyPair (java.security.KeyPair)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8