Search in sources :

Example 46 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project Conversations by iNPUTmice.

the class CryptoHelper method extractCertificateInformation.

public static Bundle extractCertificateInformation(X509Certificate certificate) {
    Bundle information = new Bundle();
    try {
        JcaX509CertificateHolder holder = new JcaX509CertificateHolder(certificate);
        X500Name subject = holder.getSubject();
        try {
            information.putString("subject_cn", subject.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        try {
            information.putString("subject_o", subject.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        X500Name issuer = holder.getIssuer();
        try {
            information.putString("issuer_cn", issuer.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        try {
            information.putString("issuer_o", issuer.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        try {
            information.putString("sha1", getFingerprintCert(certificate.getEncoded()));
        } catch (Exception e) {
        }
        return information;
    } catch (CertificateEncodingException e) {
        return information;
    }
}
Also used : Bundle(android.os.Bundle) CertificateEncodingException(java.security.cert.CertificateEncodingException) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) CertificateParsingException(java.security.cert.CertificateParsingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 47 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project nosql-java-sdk by oracle.

the class DriverTestBase method generateKeyPair.

/**
 * Generate a RAS key and certificate, return in PEM. Note that certificate
 * must has OU with opc-tenant:TestTenant, because it's used by instance
 * and resource principal testing.
 * @return a string that the first element is key and the second one is
 * certificate.
 */
protected static KeyPairInfo generateKeyPair() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);
    KeyPair keypair = keygen.generateKeyPair();
    JcaPKCS8Generator gen = new JcaPKCS8Generator(keypair.getPrivate(), null);
    StringWriter sw = new StringWriter();
    try (JcaPEMWriter pw = new JcaPEMWriter(sw)) {
        pw.writeObject(gen.generate());
    }
    String key = sw.toString();
    X500Name name = new X500Name("OU=opc-tenant:TestTenant");
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keypair.getPublic().getEncoded());
    Date start = new Date();
    Date until = Date.from(LocalDate.now().plus(3650, ChronoUnit.DAYS).atStartOfDay().toInstant(ZoneOffset.UTC));
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name, new BigInteger(10, new SecureRandom()), start, until, name, subPubKeyInfo);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(keypair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);
    Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);
    sw = new StringWriter();
    try (JcaPEMWriter pw = new JcaPEMWriter(sw)) {
        pw.writeObject(cert);
    }
    String certString = sw.toString();
    return new KeyPairInfo(key, certString, keypair);
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) LocalDate(java.time.LocalDate) StringWriter(java.io.StringWriter) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Certificate(java.security.cert.Certificate)

Example 48 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project dubbo-spi-extensions by apache.

the class IstioCitadelCertificateSigner method generateCsr.

private String generateCsr(PublicKey publicKey, ContentSigner signer) throws IOException {
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { new GeneralName(6, istioEnv.getCsrHost()) });
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, true, subjectAltNames);
    PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder(new X500Name("O=" + istioEnv.getTrustDomain()), publicKey).addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()).build(signer);
    String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded());
    if (logger.isDebugEnabled()) {
        logger.debug("CSR Request to Istio Citadel. \n" + csr);
    }
    return csr;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X500Name(org.bouncycastle.asn1.x500.X500Name) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 49 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project carapaceproxy by diennea.

the class CertificatesTestUtils method generateSampleChain.

public static Certificate[] generateSampleChain(KeyPair endUserKeypair, boolean expired) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    // Create self signed Root CA certificate
    KeyPair rootCAKeyPair = KeyPairUtils.createKeyPair(DEFAULT_KEYPAIRS_SIZE);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// issuer authority
    new X500Name("CN=rootCA"), // serial number of certificate
    BigInteger.valueOf(new Random().nextInt()), // start of validity
    new Date(), // end of certificate validity
    new Date(), // subject name of certificate
    new X500Name("CN=rootCA"), rootCAKeyPair.getPublic());
    // public key of certificate
    // Key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
    // Root certificate
    X509Certificate rootCA = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(// private key of signing authority , here it is self signed
    rootCAKeyPair.getPrivate())));
    // Create Intermediate CA cert signed by Root CA
    KeyPair intermedCAKeyPair = createKeyPair(DEFAULT_KEYPAIRS_SIZE);
    builder = new JcaX509v3CertificateBuilder(// here rootCA is issuer authority
    rootCA, BigInteger.valueOf(new Random().nextInt()), new Date(), new Date(), new X500Name("CN=IntermedCA"), intermedCAKeyPair.getPublic());
    // Key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
    // Intermediate certificate
    X509Certificate intermediateCA = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(// private key of signing authority , here it is signed by rootCA
    rootCAKeyPair.getPrivate())));
    // create end user cert signed by Intermediate CA
    // yesterday/tomorrow
    int offset = 1000 * 60 * 60 * 24;
    Date expiringDate = new Date(System.currentTimeMillis() + (expired ? -offset : +offset));
    builder = new JcaX509v3CertificateBuilder(// here intermedCA is issuer authority
    intermediateCA, BigInteger.valueOf(new Random().nextInt()), new Date(System.currentTimeMillis() - offset), expiringDate, new X500Name("CN=endUserCert"), endUserKeypair.getPublic());
    // Key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    // End-user certificate
    X509Certificate endUserCert = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(// private key of signing authority , here it is signed by intermedCA
    intermedCAKeyPair.getPrivate())));
    return new X509Certificate[] { endUserCert, intermediateCA, rootCA };
}
Also used : KeyPair(java.security.KeyPair) KeyPairUtils.createKeyPair(org.shredzone.acme4j.util.KeyPairUtils.createKeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Random(java.util.Random) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 50 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project documentproduction by qld-gov-au.

the class OcspHelper method verifyOcspResponse.

/**
 * Verifies the status and the response itself (including nonce), but not the signature.
 *
 * @param ocspResponse to be verified
 * @throws OCSPException
 * @throws RevokedCertificateException
 * @throws IOException if the default security provider can't be instantiated
 */
private void verifyOcspResponse(OCSPResp ocspResponse) throws OCSPException, RevokedCertificateException, IOException {
    verifyRespStatus(ocspResponse);
    BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
    if (basicResponse != null) {
        ResponderID responderID = basicResponse.getResponderId().toASN1Primitive();
        // https://tools.ietf.org/html/rfc6960#section-4.2.2.3
        // The basic response type contains:
        // (...)
        // either the name of the responder or a hash of the responder's
        // public key as the ResponderID
        // (...)
        // The responder MAY include certificates in the certs field of
        // BasicOCSPResponse that help the OCSP client verify the responder's
        // signature.
        X500Name name = responderID.getName();
        if (name != null) {
            findResponderCertificateByName(basicResponse, name);
        } else {
            byte[] keyHash = responderID.getKeyHash();
            if (keyHash != null) {
                findResponderCertificateByKeyHash(basicResponse, keyHash);
            } else {
                throw new OCSPException("OCSP: basic response must provide name or key hash");
            }
        }
        if (ocspResponderCertificate == null) {
            throw new OCSPException("OCSP: certificate for responder " + name + " not found");
        }
        try {
            SigUtils.checkResponderCertificateUsage(ocspResponderCertificate);
        } catch (CertificateParsingException ex) {
            // unlikely to happen because the certificate existed as an object
            LOG.error(ex.getMessage(), ex);
        }
        checkOcspSignature(ocspResponderCertificate, basicResponse);
        boolean nonceChecked = checkNonce(basicResponse);
        SingleResp[] responses = basicResponse.getResponses();
        if (responses.length != 1) {
            throw new OCSPException("OCSP: Received " + responses.length + " responses instead of 1!");
        }
        SingleResp resp = responses[0];
        Object status = resp.getCertStatus();
        if (!nonceChecked) {
            // https://tools.ietf.org/html/rfc5019
            // fall back to validating the OCSPResponse based on time
            checkOcspResponseFresh(resp);
        }
        if (status instanceof RevokedStatus) {
            RevokedStatus revokedStatus = (RevokedStatus) status;
            if (revokedStatus.getRevocationTime().compareTo(signDate) <= 0) {
                throw new RevokedCertificateException("OCSP: Certificate is revoked since " + revokedStatus.getRevocationTime(), revokedStatus.getRevocationTime());
            }
            LOG.info("The certificate was revoked after signing by OCSP " + ocspUrl + " on " + revokedStatus.getRevocationTime());
        } else if (status != CertificateStatus.GOOD) {
            throw new OCSPException("OCSP: Status of Cert is unknown");
        }
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) RevokedCertificateException(org.apache.pdfbox.examples.signature.cert.RevokedCertificateException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ResponderID(org.bouncycastle.asn1.ocsp.ResponderID) X500Name(org.bouncycastle.asn1.x500.X500Name) SingleResp(org.bouncycastle.cert.ocsp.SingleResp)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)510 X509Certificate (java.security.cert.X509Certificate)182 BigInteger (java.math.BigInteger)175 Date (java.util.Date)168 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)158 ContentSigner (org.bouncycastle.operator.ContentSigner)149 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)145 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)127 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)127 IOException (java.io.IOException)104 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)100 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)93 KeyPair (java.security.KeyPair)79 RDN (org.bouncycastle.asn1.x500.RDN)75 X500Name (sun.security.x509.X500Name)68 PrivateKey (java.security.PrivateKey)64 CertificateException (java.security.cert.CertificateException)64 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)55 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)55 SecureRandom (java.security.SecureRandom)54