Search in sources :

Example 26 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate 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 27 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method isCached.

/**
 * Is OCSP Response cached?
 *
 * @param pairIssuerSubjectList a list of pair of issuer and subject certificates
 * @return true if all of OCSP response are cached else false
 */
private boolean isCached(List<SFPair<Certificate, Certificate>> pairIssuerSubjectList) {
    long currentTimeSecond = new Date().getTime() / 1000L;
    boolean isCached = true;
    try {
        for (SFPair<Certificate, Certificate> pairIssuerSubject : pairIssuerSubjectList) {
            OCSPReq req = createRequest(pairIssuerSubject);
            CertificateID certificateId = req.getRequestList()[0].getCertID();
            LOGGER.debug(CertificateIDToString(certificateId));
            CertID cid = certificateId.toASN1Primitive();
            OcspResponseCacheKey k = new OcspResponseCacheKey(cid.getIssuerNameHash().getEncoded(), cid.getIssuerKeyHash().getEncoded(), cid.getSerialNumber().getValue());
            SFPair<Long, String> res = OCSP_RESPONSE_CACHE.get(k);
            if (res == null) {
                LOGGER.debug("Not all OCSP responses for the certificate is in the cache.");
                isCached = false;
                break;
            } else if (currentTimeSecond - CACHE_EXPIRATION_IN_SECONDS > res.left) {
                LOGGER.debug("Cache for CertID expired.");
                isCached = false;
                break;
            } else {
                try {
                    validateRevocationStatusMain(pairIssuerSubject, res.right);
                } catch (SFOCSPException ex) {
                    LOGGER.debug("Cache includes invalid OCSPResponse. " + "Will download the OCSP cache from Snowflake OCSP server");
                    isCached = false;
                }
            }
        }
    } catch (IOException ex) {
        LOGGER.debug("Failed to encode CertID.");
    }
    return isCached;
}
Also used : CertID(org.bouncycastle.asn1.ocsp.CertID) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 28 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method getTrustManager.

/**
 * Get TrustManager for the algorithm. This is mainly used to get the JVM default trust manager
 * and cache all of the root CA.
 *
 * @param algorithm algorithm.
 * @return TrustManager object.
 */
private X509TrustManager getTrustManager(String algorithm) {
    try {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm);
        factory.init((KeyStore) null);
        X509TrustManager ret = null;
        for (TrustManager tm : factory.getTrustManagers()) {
            // Manager here.
            if (tm instanceof X509TrustManager) {
                ret = (X509TrustManager) tm;
                break;
            }
        }
        if (ret == null) {
            return null;
        }
        synchronized (ROOT_CA_LOCK) {
            // cache root CA certificates for later use.
            if (ROOT_CA.isEmpty()) {
                for (X509Certificate cert : ret.getAcceptedIssuers()) {
                    Certificate bcCert = Certificate.getInstance(cert.getEncoded());
                    ROOT_CA.put(bcCert.getSubject().hashCode(), bcCert);
                }
            }
        }
        return ret;
    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateEncodingException ex) {
        throw new SSLInitializationException(ex.getMessage(), ex);
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) SSLInitializationException(org.apache.http.ssl.SSLInitializationException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 29 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method getPairIssuerSubject.

/**
 * Creates a pair of Issuer and Subject certificates
 *
 * @param bcChain a list of bouncy castle Certificate
 * @return a list of paif of Issuer and Subject certificates
 */
private List<SFPair<Certificate, Certificate>> getPairIssuerSubject(List<Certificate> bcChain) throws CertificateException {
    List<SFPair<Certificate, Certificate>> pairIssuerSubject = new ArrayList<>();
    for (int i = 0, len = bcChain.size(); i < len; ++i) {
        Certificate bcCert = bcChain.get(i);
        if (bcCert.getIssuer().equals(bcCert.getSubject())) {
            // skipping ROOT CA
            continue;
        }
        if (i < len - 1) {
            pairIssuerSubject.add(SFPair.of(bcChain.get(i + 1), bcChain.get(i)));
        } else {
            // no root CA certificate is attached in the certificate chain, so
            // getting one from the root CA from JVM.
            Certificate issuer = ROOT_CA.get(bcCert.getIssuer().hashCode());
            if (issuer == null) {
                throw new CertificateException("Failed to find the root CA.", new SFOCSPException(OCSPErrorCode.NO_ROOTCA_FOUND, "Failed to find the root CA."));
            }
            pairIssuerSubject.add(SFPair.of(issuer, bcChain.get(i)));
        }
    }
    return pairIssuerSubject;
}
Also used : CertificateException(java.security.cert.CertificateException) SFPair(net.snowflake.client.util.SFPair) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 30 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project axelor-open-suite by axelor.

the class X509Generator method getAuthorityKeyIdentifier.

/**
 * Returns the <code>AuthorityKeyIdentifier</code> corresponding to a given <code>PublicKey</code>
 *
 * @param publicKey the given public key
 * @param issuer the certificate issuer
 * @param serial the certificate serial number
 * @return the authority key identifier of the public key
 * @throws IOException
 */
private AuthorityKeyIdentifier getAuthorityKeyIdentifier(PublicKey publicKey, String issuer, BigInteger serial) throws IOException {
    InputStream input;
    SubjectPublicKeyInfo keyInfo;
    ASN1EncodableVector vector;
    input = new ByteArrayInputStream(publicKey.getEncoded());
    try (final ASN1InputStream is = new ASN1InputStream(input)) {
        keyInfo = SubjectPublicKeyInfo.getInstance((ASN1Sequence) is.readObject());
    }
    vector = new ASN1EncodableVector();
    vector.add(new GeneralName(new X509Name(issuer)));
    return new AuthorityKeyIdentifier(keyInfo, GeneralNames.getInstance(new DERSequence(vector)), serial);
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) X509Name(org.bouncycastle.asn1.x509.X509Name) DERSequence(org.bouncycastle.asn1.DERSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) GeneralName(org.bouncycastle.asn1.x509.GeneralName) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)

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