use of com.github.zhenwei.core.asn1.x509.Certificate 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;
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project conformance-suite by openid-certification.
the class ValidateMTLSCertificatesAsX509 method verifyECPrivateKey.
private void verifyECPrivateKey(String certString, String keyString, byte[] decodedKey, X509Certificate certificate) {
PrivateKey privateKey;
try {
// try to generate private key is PKCS8
KeySpec kspec = new PKCS8EncodedKeySpec(decodedKey);
privateKey = KeyFactory.getInstance("EC", "BC").generatePrivate(kspec);
} catch (InvalidKeySpecException e) {
try {
// try to generate private key isn't PKCS8
ASN1Sequence seq = ASN1Sequence.getInstance(decodedKey);
org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
byte[] server_pkcs8 = new PrivateKeyInfo(algId, pKey).getEncoded();
privateKey = KeyFactory.getInstance("EC", "BC").generatePrivate(new PKCS8EncodedKeySpec(server_pkcs8));
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException ex) {
throw error("Couldn't generate private key", e, args("key", keyString));
}
} catch (NoSuchProviderException | NoSuchAlgorithmException e) {
throw error("Provider or Algorithm of KeyFactory is invalid", e);
}
// TODO: Need to check that the private key and the certificate match
// This check isn't sure yet
ECPublicKey ecPublicKey = (ECPublicKey) certificate.getPublicKey();
if (!((ECPrivateKey) privateKey).getParameters().equals(ecPublicKey.getParameters())) {
throw error("MTLS Private Key and Cert do not match", args("cert", certString, "key", keyString));
}
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project conformance-suite by openid-certification.
the class GenerateMTLSCertificateFromJWKs method evaluate.
@Override
@PreEnvironment(required = "client_jwks", strings = "client_name")
@PostEnvironment(required = "mutual_tls_authentication")
public Environment evaluate(Environment env) {
JWKSet jwks;
try {
jwks = JWKSet.parse(env.getObject("client_jwks").toString());
} catch (ParseException e) {
throw error("Failed to parse JWKs", e);
}
JWK jwk = jwks.getKeys().get(0);
KeyPair keyPair = toKeyPair(jwk);
String clientName = env.getString("client_name");
long now = System.currentTimeMillis();
Date notBefore = new Date(now);
Calendar calendar = Calendar.getInstance();
calendar.setTime(notBefore);
calendar.add(Calendar.YEAR, 1);
Date notAfter = calendar.getTime();
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(now));
certGen.setSubjectDN(new X500Principal("cn=" + clientName));
certGen.setIssuerDN(new X500Principal("cn=" + clientName));
certGen.setNotBefore(notBefore);
certGen.setNotAfter(notAfter);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm(getSigningAlgorithm(jwk));
certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
X509Certificate cert;
try {
cert = certGen.generate(keyPair.getPrivate(), "BC");
} catch (CertificateEncodingException | InvalidKeyException | IllegalStateException | NoSuchProviderException | NoSuchAlgorithmException | SignatureException e) {
throw error("Failed to generate certificate", e);
}
JsonObject mtls = new JsonObject();
try {
mtls.addProperty("cert", Base64.getEncoder().encodeToString(cert.getEncoded()));
} catch (CertificateEncodingException e) {
throw error("Error encoding certificate", e);
}
mtls.addProperty("key", Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
env.putObject("mutual_tls_authentication", mtls);
logSuccess("Generated client MTLS certificate", args("mutual_tls_authentication", mtls));
return env;
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project carapaceproxy by diennea.
the class CertificatesTest method testUploadTypedCertificatesWithDaysBeforeRenewal.
@Test
@Parameters({ "acme", "manual" })
public void testUploadTypedCertificatesWithDaysBeforeRenewal(String type) throws Exception {
configureAndStartServer();
int port = server.getLocalPort();
DynamicCertificatesManager dynCertsMan = server.getDynamicCertificatesManager();
KeyPair endUserKeyPair = KeyPairUtils.createKeyPair(DEFAULT_KEYPAIRS_SIZE);
Certificate[] chain = generateSampleChain(endUserKeyPair, false);
byte[] chainData = createKeystore(chain, endUserKeyPair.getPrivate());
try (RawHttpClient client = new RawHttpClient("localhost", DEFAULT_ADMIN_PORT)) {
// Create
HttpResponse resp = uploadCertificate("localhost2", "type=" + type + "&daysbeforerenewal=10", chainData, client, credentials);
if (type.equals("manual")) {
assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
} else {
CertificateData data = dynCertsMan.getCertificateDataForDomain("localhost2");
assertNotNull(data);
assertEquals(10, data.getDaysBeforeRenewal());
}
// negative value
resp = uploadCertificate("localhost-negative", "type=" + type + "&daysbeforerenewal=-10", chainData, client, credentials);
if (type.equals("manual")) {
assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
} else {
assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' has to be a positive number"));
}
// default value
uploadCertificate("localhost-default", "type=" + type, chainData, client, credentials);
CertificateData data = dynCertsMan.getCertificateDataForDomain("localhost-default");
assertNotNull(data);
assertEquals(type.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, data.getDaysBeforeRenewal());
// Update
uploadCertificate("localhost2", "type=" + type + "&daysbeforerenewal=45", chainData, client, credentials);
if (type.equals("manual")) {
assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
} else {
data = dynCertsMan.getCertificateDataForDomain("localhost2");
assertNotNull(data);
assertEquals(45, data.getDaysBeforeRenewal());
}
// negative value
resp = uploadCertificate("localhost2", "type=" + type + "&daysbeforerenewal=-10", chainData, client, credentials);
if (type.equals("manual")) {
assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
} else {
assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' has to be a positive number"));
}
// default value
uploadCertificate("localhost2", "type=" + type, chainData, client, credentials);
data = dynCertsMan.getCertificateDataForDomain("localhost2");
assertNotNull(data);
assertEquals(type.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, data.getDaysBeforeRenewal());
// changing the type (acme <-> manual)
String other = type.equals("manual") ? "acme" : "manual";
uploadCertificate("localhost2", "type=" + other, chainData, client, credentials);
data = dynCertsMan.getCertificateDataForDomain("localhost2");
assertNotNull(data);
assertEquals(other.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, data.getDaysBeforeRenewal());
SSLCertificateConfiguration config = server.getCurrentConfiguration().getCertificates().get("localhost2");
assertEquals(other.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, config.getDaysBeforeRenewal());
// checking for "certificate.X.daysbeforerenewal" property delete
ConfigurationStore store = server.getDynamicConfigurationStore();
assertEquals(other.equals("acme"), store.anyPropertyMatches((k, v) -> {
if (k.matches("certificate\\.[0-9]+\\.hostname") && v.equals("localhost2")) {
return store.getProperty(k.replace("hostname", "daysbeforerenewal"), null) != null;
}
return false;
}));
}
}
use of com.github.zhenwei.core.asn1.x509.Certificate 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 };
}
Aggregations