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);
}
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;
}
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);
}
}
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;
}
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);
}
Aggregations