Search in sources :

Example 16 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project acme4j by shred.

the class CSRBuilderTest method csrTest.

/**
 * Checks if the CSR contains the right parameters.
 * <p>
 * This is not supposed to be a Bouncy Castle test. If the
 * {@link PKCS10CertificationRequest} contains the right parameters, we assume that
 * Bouncy Castle encodes it properly.
 */
private void csrTest(PKCS10CertificationRequest csr) {
    X500Name name = csr.getSubject();
    try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
        softly.assertThat(name.getRDNs(BCStyle.CN)).as("CN").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("abc.de");
        softly.assertThat(name.getRDNs(BCStyle.C)).as("C").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("XX");
        softly.assertThat(name.getRDNs(BCStyle.L)).as("L").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testville");
        softly.assertThat(name.getRDNs(BCStyle.O)).as("O").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testing Co");
        softly.assertThat(name.getRDNs(BCStyle.OU)).as("OU").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testunit");
        softly.assertThat(name.getRDNs(BCStyle.ST)).as("ST").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("ABC");
    }
    Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    assertThat(attr).hasSize(1);
    ASN1Encodable[] extensions = attr[0].getAttrValues().toArray();
    assertThat(extensions).hasSize(1);
    GeneralNames names = GeneralNames.fromExtensions((Extensions) extensions[0], Extension.subjectAlternativeName);
    assertThat(names.getNames()).filteredOn(gn -> gn.getTagNo() == GeneralName.dNSName).extracting(gn -> ASN1IA5String.getInstance(gn.getName()).getString()).containsExactlyInAnyOrder("abc.de", "fg.hi", "jklm.no", "pqr.st", "uv.wx", "y.z", "*.wild.card", "ide1.nt", "ide2.nt", "ide3.nt");
    assertThat(names.getNames()).filteredOn(gn -> gn.getTagNo() == GeneralName.iPAddress).extracting(gn -> getIP(gn.getName()).getHostAddress()).containsExactlyInAnyOrder("192.168.0.1", "192.168.0.2", "10.0.0.1", "10.0.0.2", "fd00:0:0:0:0:0:0:1", "fd00:0:0:0:0:0:0:2", "192.168.5.5", "192.168.5.6", "192.168.5.7");
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Identifier(org.shredzone.acme4j.Identifier) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) Extension(org.bouncycastle.asn1.x509.Extension) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Security(java.security.Security) DEROctetString(org.bouncycastle.asn1.DEROctetString) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) InetAddress(java.net.InetAddress) X500Name(org.bouncycastle.asn1.x500.X500Name) BeforeAll(org.junit.jupiter.api.BeforeAll) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ASN1IA5String(org.bouncycastle.asn1.ASN1IA5String) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) PEMParser(org.bouncycastle.openssl.PEMParser) StringWriter(java.io.StringWriter) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) StandardCharsets(java.nio.charset.StandardCharsets) Extensions(org.bouncycastle.asn1.x509.Extensions) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Test(org.junit.jupiter.api.Test) GeneralName(org.bouncycastle.asn1.x509.GeneralName) StringReader(java.io.StringReader) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions)

Example 17 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project acme4j by shred.

the class SMIMECSRBuilderTest method smimeCsrTest.

/**
 * Checks if the S/MIME CSR contains the right parameters.
 * <p>
 * This is not supposed to be a Bouncy Castle test. If the
 * {@link PKCS10CertificationRequest} contains the right parameters, we assume that
 * Bouncy Castle encodes it properly.
 */
private void smimeCsrTest(PKCS10CertificationRequest csr) {
    X500Name name = csr.getSubject();
    try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
        softly.assertThat(name.getRDNs(BCStyle.CN)).as("CN").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("mail@example.com");
        softly.assertThat(name.getRDNs(BCStyle.C)).as("C").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("XX");
        softly.assertThat(name.getRDNs(BCStyle.L)).as("L").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testville");
        softly.assertThat(name.getRDNs(BCStyle.O)).as("O").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testing Co");
        softly.assertThat(name.getRDNs(BCStyle.OU)).as("OU").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testunit");
        softly.assertThat(name.getRDNs(BCStyle.ST)).as("ST").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("ABC");
    }
    Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    assertThat(attr).hasSize(1);
    ASN1Encodable[] extensions = attr[0].getAttrValues().toArray();
    assertThat(extensions).hasSize(1);
    GeneralNames names = GeneralNames.fromExtensions((Extensions) extensions[0], Extension.subjectAlternativeName);
    assertThat(names.getNames()).filteredOn(gn -> gn.getTagNo() == GeneralName.rfc822Name).extracting(gn -> DERIA5String.getInstance(gn.getName()).getString()).containsExactlyInAnyOrder("mail@example.com", "info@example.com", "sales@example.com", "shop@example.com", "support@example.com", "help@example.com");
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) Extension(org.bouncycastle.asn1.x509.Extension) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Security(java.security.Security) DERBitString(org.bouncycastle.asn1.DERBitString) AddressException(jakarta.mail.internet.AddressException) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) InternetAddress(jakarta.mail.internet.InternetAddress) X500Name(org.bouncycastle.asn1.x500.X500Name) BeforeAll(org.junit.jupiter.api.BeforeAll) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) UTF_8(java.nio.charset.StandardCharsets.UTF_8) PEMParser(org.bouncycastle.openssl.PEMParser) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Test(org.junit.jupiter.api.Test) GeneralName(org.bouncycastle.asn1.x509.GeneralName) StringReader(java.io.StringReader) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) KeyPairUtils(org.shredzone.acme4j.util.KeyPairUtils) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions)

Example 18 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project credhub by cloudfoundry.

the class CertificateReader method isCa.

public boolean isCa() {
    final Extensions extensions = certificateHolder.getExtensions();
    BasicConstraints basicConstraints = null;
    if (extensions != null) {
        basicConstraints = BasicConstraints.fromExtensions(Extensions.getInstance(extensions));
    }
    return basicConstraints != null && basicConstraints.isCA();
}
Also used : Extensions(org.bouncycastle.asn1.x509.Extensions) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 19 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 20 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project poi by apache.

the class PkiTestUtils method createOcspResp.

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
    // request
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);
    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);
    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }
    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
    }
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
    return ocspResp;
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Aggregations

Extensions (org.bouncycastle.asn1.x509.Extensions)113 Extension (org.bouncycastle.asn1.x509.Extension)89 IOException (java.io.IOException)72 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Enumeration (java.util.Enumeration)57 HashSet (java.util.HashSet)49 DEROctetString (org.bouncycastle.asn1.DEROctetString)49 X500Name (org.bouncycastle.asn1.x500.X500Name)46 BigInteger (java.math.BigInteger)45 Set (java.util.Set)36 X509Certificate (java.security.cert.X509Certificate)35 Date (java.util.Date)35 GeneralName (org.bouncycastle.asn1.x509.GeneralName)35 ContentSigner (org.bouncycastle.operator.ContentSigner)32 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)29 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)28 ArrayList (java.util.ArrayList)28 CertificateException (java.security.cert.CertificateException)27 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)27