Search in sources :

Example 21 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project modules by assimbly.

the class CertificatesUtil method createSubjectKeyId.

/**
 * Creates the hash value of the public key.
 *
 * @param publicKey of the certificate
 *
 * @return SubjectKeyIdentifier hash
 *
 * @throws OperatorCreationException
 */
private static SubjectKeyIdentifier createSubjectKeyId(final PublicKey publicKey) throws OperatorCreationException {
    final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    final DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    return new X509ExtensionUtils(digCalc).createSubjectKeyIdentifier(publicKeyInfo);
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 22 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project modules by assimbly.

the class CertificatesUtil method selfsignCertificate2.

public static Certificate selfsignCertificate2(KeyPair keyPair, String subjectDN) throws OperatorCreationException, CertificateException, IOException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    long now = System.currentTimeMillis();
    Date startDate = new Date(now);
    X500Name dnName = new X500Name("CN=" + subjectDN);
    // <-- Using the current timestamp as the certificate serial number
    BigInteger certSerialNumber = new BigInteger(Long.toString(now));
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    // <-- 2 Yr validity
    calendar.add(Calendar.YEAR, 2);
    Date endDate = calendar.getTime();
    // <-- Use appropriate signature algorithm based on your keyPair algorithm.
    String signatureAlgorithm = "SHA256WithRSA";
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic());
    // Extensions --------------------------
    // Basic Constraints
    // <-- true for CA, false for EndEntity
    BasicConstraints basicConstraints = new BasicConstraints(true);
    // Basic Constraints is usually marked as critical.
    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);
    return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) Provider(java.security.Provider) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 23 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project modules by assimbly.

the class CertificatesUtil method selfsignCertificate.

/**
 * Generates a self signed certificate using the BouncyCastle lib.
 *
 * @param keyPair used for signing the certificate with PrivateKey
 * @param hashAlgorithm Hash function
 * @param cn Common Name to be used in the subject dn
 * @param days validity period in days of the certificate
 *
 * @return self-signed X509Certificate
 *
 * @throws OperatorCreationException on creating a key id
 * @throws CertIOException on building JcaContentSignerBuilder
 * @throws CertificateException on getting certificate from provider
 */
public static X509Certificate selfsignCertificate(final KeyPair keyPair, final String hashAlgorithm, final String cn, final int days) throws OperatorCreationException, CertificateException, CertIOException {
    final Instant now = Instant.now();
    final Date notBefore = Date.from(now);
    final Date notAfter = Date.from(now.plus(Duration.ofDays(days)));
    final ContentSigner contentSigner = new JcaContentSignerBuilder(hashAlgorithm).build(keyPair.getPrivate());
    final X500Name x500Name = new X500Name("CN=" + cn);
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(x500Name, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic()).addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(keyPair.getPublic())).addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(keyPair.getPublic())).addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    return new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certificateBuilder.build(contentSigner));
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) Instant(java.time.Instant) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) Date(java.util.Date) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 24 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project identity-credential by google.

the class CertificateGenerator method generateCertificate.

static X509Certificate generateCertificate(DataMaterial data, CertificateMaterial certMaterial, KeyMaterial keyMaterial) throws CertIOException, CertificateException, OperatorCreationException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    Optional<X509Certificate> issuerCert = keyMaterial.issuerCertificate();
    X500Name subjectDN = new X500Name(data.subjectDN());
    // doesn't work, get's reordered
    // issuerCert.isPresent() ? new X500Name(issuerCert.get().getSubjectX500Principal().getName()) : subjectDN;
    X500Name issuerDN = new X500Name(data.issuerDN());
    ContentSigner contentSigner = new JcaContentSignerBuilder(keyMaterial.signingAlgorithm()).build(keyMaterial.signingKey());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, certMaterial.serialNumber(), certMaterial.startDate(), certMaterial.endDate(), subjectDN, keyMaterial.publicKey());
    // Extensions --------------------------
    JcaX509ExtensionUtils jcaX509ExtensionUtils;
    try {
        jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    if (issuerCert.isPresent()) {
        try {
            // adds 3 more fields, not present in other cert
            // AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get());
            AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get().getPublicKey());
            certBuilder.addExtension(Extension.authorityKeyIdentifier, NOT_CRITICAL, authorityKeyIdentifier);
        } catch (IOException e) {
            // CertificateEncodingException |
            throw new RuntimeException(e);
        }
    }
    SubjectKeyIdentifier subjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyMaterial.publicKey());
    certBuilder.addExtension(Extension.subjectKeyIdentifier, NOT_CRITICAL, subjectKeyIdentifier);
    KeyUsage keyUsage = new KeyUsage(certMaterial.keyUsage());
    certBuilder.addExtension(Extension.keyUsage, CRITICAL, keyUsage);
    // IssuerAlternativeName
    Optional<String> issuerAlternativeName = data.issuerAlternativeName();
    if (issuerAlternativeName.isPresent()) {
        GeneralNames issuerAltName = new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, issuerAlternativeName.get()));
        certBuilder.addExtension(Extension.issuerAlternativeName, NOT_CRITICAL, issuerAltName);
    }
    // Basic Constraints
    int pathLengthConstraint = certMaterial.pathLengthConstraint();
    if (pathLengthConstraint != CertificateMaterial.PATHLENGTH_NOT_A_CA) {
        // TODO doesn't work for certificate chains != 2 in size
        BasicConstraints basicConstraints = new BasicConstraints(pathLengthConstraint);
        certBuilder.addExtension(Extension.basicConstraints, CRITICAL, basicConstraints);
    }
    Optional<String> extendedKeyUsage = certMaterial.extendedKeyUsage();
    if (extendedKeyUsage.isPresent()) {
        KeyPurposeId keyPurpose = KeyPurposeId.getInstance(new ASN1ObjectIdentifier(extendedKeyUsage.get()));
        ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(new KeyPurposeId[] { keyPurpose });
        certBuilder.addExtension(Extension.extendedKeyUsage, CRITICAL, extKeyUsage);
    }
    // DEBUG setProvider(bcProvider) removed before getCertificate
    return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Provider(java.security.Provider) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 25 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project TLS-Scanner by tls-attacker.

the class TrustAnchorManager method getFullCaCertificateSet.

private Set<Certificate> getFullCaCertificateSet() {
    Set<Certificate> certificateSet = new HashSet<>();
    for (CertificateEntry entry : trustAnchors.values()) {
        InputStream resourceAsStream = TrustAnchorManager.class.getClassLoader().getResourceAsStream("trust/" + entry.getFingerprint() + ".pem");
        try {
            org.bouncycastle.crypto.tls.Certificate cert = PemUtil.readCertificate(resourceAsStream);
            certificateSet.add(cert.getCertificateAt(0));
        } catch (IOException | CertificateException ex) {
            LOGGER.error("Could not load Certificate:" + entry.getSubjectName() + "/" + entry.getFingerprint(), ex);
        }
    }
    return certificateSet;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) HashSet(java.util.HashSet)

Aggregations

IOException (java.io.IOException)242 X509Certificate (java.security.cert.X509Certificate)216 Date (java.util.Date)133 X500Name (org.bouncycastle.asn1.x500.X500Name)133 BigInteger (java.math.BigInteger)120 ContentSigner (org.bouncycastle.operator.ContentSigner)102 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)101 GeneralName (org.bouncycastle.asn1.x509.GeneralName)100 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)96 CertificateException (java.security.cert.CertificateException)95 ArrayList (java.util.ArrayList)90 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)85 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)82 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)78 GeneralSecurityException (java.security.GeneralSecurityException)69 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)62 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)62 Extension (org.bouncycastle.asn1.x509.Extension)61 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)60 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)59