Search in sources :

Example 51 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project dcache-cta by dCache.

the class CtaNearlineStorageTest method generateSelfSignedCert.

private void generateSelfSignedCert() throws GeneralSecurityException, OperatorCreationException, IOException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider());
    keyPairGenerator.initialize(2048, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    long notBefore = System.currentTimeMillis();
    long notAfter = notBefore + TimeUnit.DAYS.toMillis(1);
    X500Name subjectDN = new X500Name("CN=localhost, O=dCache.org");
    X500Name issuerDN = subjectDN;
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuerDN, BigInteger.ONE, new Date(notBefore), new Date(notAfter), subjectDN, subjectPublicKeyInfo).addExtension(Extension.basicConstraints, true, new BasicConstraints(true)).addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
    String signatureAlgorithm = "SHA256WithRSA";
    // sign with own key
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
    var cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    try (OutputStream certOut = Files.newOutputStream(certFile.toPath(), CREATE, TRUNCATE_EXISTING, WRITE);
        OutputStream keyOut = Files.newOutputStream(keyFile.toPath(), CREATE, TRUNCATE_EXISTING, WRITE)) {
        CertificateUtils.saveCertificate(certOut, cert, Encoding.PEM);
        CertificateUtils.savePrivateKey(keyOut, keyPair.getPrivate(), Encoding.PEM, null, null);
    }
}
Also used : KeyPair(java.security.KeyPair) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) OutputStream(java.io.OutputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyPairGenerator(java.security.KeyPairGenerator) 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) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 52 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project SAMLRaider by CompassSecurity.

the class BurpCertificateBuilder method generateX509Certificate.

/**
 * Creates a X.509v3 Certificate. The values of "this" object are used for
 * the building process.
 *
 * @param privateKey
 *            which signes the certificates
 * @return certificate object
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchAlgorithmException
 * @throws SignatureException
 * @throws IOException
 */
private X509Certificate generateX509Certificate(PrivateKey privateKey) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, IOException {
    if (version != 3) {
        throw new UnsupportedOperationException("Not implemented yet.");
    }
    certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.setSerialNumber(serial);
    certificateGenerator.setIssuerDN(this.issuer);
    certificateGenerator.setNotBefore(notBefore);
    certificateGenerator.setNotAfter(notAfter);
    certificateGenerator.setSubjectDN(subject);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setPublicKey(publicKey);
    if (hasBasicConstraints) {
        if (isCA && hasNoPathLimit) {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
        } else if (isCA && !hasNoPathLimit) {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(pathLimit));
        } else {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        }
    }
    if (keyUsage.size() > 0) {
        int allKeyUsages = 0;
        for (int i : keyUsage) {
            allKeyUsages |= i;
        }
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(allKeyUsages));
    }
    if (extendedKeyUsage.size() > 0) {
        ASN1EncodableVector allExtendedKeyUsages = new ASN1EncodableVector();
        for (KeyPurposeId i : extendedKeyUsage) {
            allExtendedKeyUsages.add(i);
        }
        certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(allExtendedKeyUsages));
    }
    if (subjectAlternativeName.size() > 0) {
        GeneralNames generalNames = new GeneralNames(subjectAlternativeName.toArray(new GeneralName[subjectAlternativeName.size()]));
        certificateGenerator.addExtension(X509Extensions.SubjectAlternativeName, true, generalNames);
    }
    if (setSubjectKeyIdentifier == true) {
        JcaX509ExtensionUtils j = new JcaX509ExtensionUtils();
        certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, j.createSubjectKeyIdentifier(publicKey));
    }
    if (!subjectKeyIdentifier.isEmpty() && setSubjectKeyIdentifier == false) {
        byte[] ski = CertificateHelper.hexStringToByteArray(subjectKeyIdentifier);
        SubjectKeyIdentifier aKI = new SubjectKeyIdentifier(ski);
        certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, true, aKI);
    }
    if (issuerAlternativeName.size() > 0) {
        GeneralNames generalNames = new GeneralNames(issuerAlternativeName.toArray(new GeneralName[issuerAlternativeName.size()]));
        certificateGenerator.addExtension(X509Extensions.IssuerAlternativeName, true, generalNames);
    }
    if (setAuthorityKeyIdentifier == true && issuerCertificate != null) {
        JcaX509ExtensionUtils j = new JcaX509ExtensionUtils();
        certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, true, j.createAuthorityKeyIdentifier(issuerCertificate));
    }
    if (!authorityKeyIdentifier.isEmpty() && setAuthorityKeyIdentifier == false) {
        byte[] aki = CertificateHelper.hexStringToByteArray(authorityKeyIdentifier);
        AuthorityKeyIdentifier aKI = new AuthorityKeyIdentifier(aki);
        certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, true, aKI);
    }
    for (BurpCertificateExtension e : burpCertificateExtensions) {
        // http://bouncycastle.sourcearchive.com/documentation/1.43/classorg_1_1bouncycastle_1_1x509_1_1X509V3CertificateGenerator_fd5118a4eaa4870e5fbf6efc02f10c00.html#fd5118a4eaa4870e5fbf6efc02f10c00
        // Finally!!!
        ASN1Encodable extension = X509ExtensionUtil.fromExtensionValue(e.getExtensionValue());
        certificateGenerator.addExtension(e.getOid(), e.isCritical(), extension);
    }
    return certificateGenerator.generate(privateKey);
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) BurpCertificateExtension(model.BurpCertificateExtension) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 53 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project nifi-registry 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 54 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project nifi-registry by apache.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));
        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // Sign the certificate
        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)

Aggregations

ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)35 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)24 KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)21 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)19 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)19 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)18 X500Name (org.bouncycastle.asn1.x500.X500Name)17 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)17 ContentSigner (org.bouncycastle.operator.ContentSigner)17 Date (java.util.Date)16 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 X509Certificate (java.security.cert.X509Certificate)13 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)12 DEROctetString (org.bouncycastle.asn1.DEROctetString)11 Extension (org.bouncycastle.asn1.x509.Extension)11 GeneralName (org.bouncycastle.asn1.x509.GeneralName)11 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)10 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)9 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8