use of com.google.cloud.security.privateca.v1.KeyUsage in project cloudstack by apache.
the class CertUtils method generateV3Certificate.
public static X509Certificate generateV3Certificate(final X509Certificate caCert, final KeyPair caKeyPair, final PublicKey clientPublicKey, final String subject, final String signatureAlgorithm, final int validityDays, final List<String> dnsNames, final List<String> publicIPAddresses) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, InvalidKeyException, SignatureException, OperatorCreationException {
final DateTime now = DateTime.now(DateTimeZone.UTC);
final BigInteger serial = generateRandomBigInt();
final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
final X509v3CertificateBuilder certBuilder;
if (caCert == null) {
// Generate CA certificate
certBuilder = new JcaX509v3CertificateBuilder(new X500Name(subject), serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Name(subject), clientPublicKey);
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
} else {
// Generate client certificate
certBuilder = new JcaX509v3CertificateBuilder(caCert, serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Principal(subject), clientPublicKey);
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert));
}
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(clientPublicKey));
final List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
if (publicIPAddresses != null) {
for (final String publicIPAddress : new HashSet<>(publicIPAddresses)) {
if (StringUtils.isEmpty(publicIPAddress)) {
continue;
}
subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, publicIPAddress));
}
}
if (dnsNames != null) {
for (final String dnsName : new HashSet<>(dnsNames)) {
if (StringUtils.isEmpty(dnsName)) {
continue;
}
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName));
}
}
if (subjectAlternativeNames.size() > 0) {
final GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[] {})));
certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
}
final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(caKeyPair.getPrivate());
final X509CertificateHolder certHolder = certBuilder.build(signer);
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
if (caCert != null) {
cert.verify(caCert.getPublicKey());
} else {
cert.verify(caKeyPair.getPublic());
}
return cert;
}
use of com.google.cloud.security.privateca.v1.KeyUsage in project zaproxy by zaproxy.
the class SslCertificateUtils method createRootCA.
/**
* Creates a new Root CA certificate and returns private and public key as {@link KeyStore}. The
* {@link KeyStore#getDefaultType()} is used.
*
* @return
* @throws NoSuchAlgorithmException If no providers are found for 'RSA' key pair generator or
* 'SHA1PRNG' Secure random number generator
* @throws IllegalStateException in case of errors during assembling {@link KeyStore}
*/
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
final Date startDate = Calendar.getInstance().getTime();
final Date expireDate = new Date(startDate.getTime() + DEFAULT_VALIDITY_IN_MS);
final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
final KeyPair keypair = g.genKeyPair();
final PrivateKey privKey = keypair.getPrivate();
final PublicKey pubKey = keypair.getPublic();
Security.addProvider(new BouncyCastleProvider());
Random rnd = new Random();
// using the hash code of the user's name and home path, keeps anonymity
// but also gives user a chance to distinguish between each other
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode()));
namebld.addRDN(BCStyle.O, "OWASP Root CA");
namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
namebld.addRDN(BCStyle.C, "xx");
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);
KeyStore ks = null;
try {
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey);
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setKeyEntry(org.parosproxy.paros.security.SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, org.parosproxy.paros.security.SslCertificateService.PASSPHRASE, new Certificate[] { cert });
} catch (final Exception e) {
throw new IllegalStateException("Errors during assembling root CA.", e);
}
return ks;
}
use of com.google.cloud.security.privateca.v1.KeyUsage in project MOPP-Android by open-eid.
the class Certificate method create.
public static Certificate create(ByteString data) throws IOException {
X509CertificateHolder certificate = new X509CertificateHolder(data.toByteArray());
Extensions extensions = certificate.getExtensions();
CertificatePolicies certificatePolicies = CertificatePolicies.fromExtensions(extensions);
EIDType type = EIDType.parse(certificatePolicies);
RDN[] rdNs = certificate.getSubject().getRDNs(ASN1ObjectIdentifier.getInstance(BCStyle.CN));
String commonName = rdNs[0].getFirst().getValue().toString().trim();
RDN[] rdSNNs = certificate.getSubject().getRDNs(ASN1ObjectIdentifier.getInstance(BCStyle.SURNAME));
RDN[] rdGNNs = certificate.getSubject().getRDNs(ASN1ObjectIdentifier.getInstance(BCStyle.GIVENNAME));
RDN[] rdSERIALNs = certificate.getSubject().getRDNs(ASN1ObjectIdentifier.getInstance(BCStyle.SERIALNUMBER));
// http://www.etsi.org/deliver/etsi_en/319400_319499/31941201/01.01.01_60/en_31941201v010101p.pdf
final List<String> types = Arrays.asList("PAS", "IDC", "PNO", "TAX", "TIN");
String serialNR = rdSERIALNs.length == 0 ? "" : rdSERIALNs[0].getFirst().getValue().toString().trim();
if (serialNR.length() > 6 && (types.contains(serialNR.substring(0, 3)) || serialNR.charAt(2) == ':') && serialNR.charAt(5) == '-')
serialNR = serialNR.substring(6);
String friendlyName = rdSNNs.length == 0 || rdGNNs.length == 0 ? commonName : rdSNNs[0].getFirst().getValue().toString().trim() + "," + rdGNNs[0].getFirst().getValue().toString().trim() + "," + serialNR;
Instant notAfter = Instant.ofEpochMilli(certificate.getNotAfter().getTime());
boolean ellipticCurve = certificate.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey);
KeyUsage keyUsage = KeyUsage.fromExtensions(extensions);
ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.fromExtensions(extensions);
if (extendedKeyUsage == null) {
extendedKeyUsage = new ExtendedKeyUsage(new KeyPurposeId[] {});
}
return new AutoValue_Certificate(type, commonName, friendlyName, notAfter, ellipticCurve, keyUsage, extendedKeyUsage, data);
}
use of com.google.cloud.security.privateca.v1.KeyUsage in project LinLong-Java by zhenwei1108.
the class JcaJceUtils method validateServerCertUsage.
public static void validateServerCertUsage(X509Certificate x509Certificate) throws CertificateException {
try {
X509CertificateHolder cert = new X509CertificateHolder(x509Certificate.getEncoded());
KeyUsage keyUsage = KeyUsage.fromExtensions(cert.getExtensions());
if (keyUsage != null) {
if (keyUsage.hasUsages(KeyUsage.keyCertSign)) {
throw new CertificateException("Key usage must not contain keyCertSign");
}
if (!(keyUsage.hasUsages(KeyUsage.digitalSignature) || keyUsage.hasUsages(KeyUsage.keyEncipherment))) {
throw new CertificateException("Key usage must be none, digitalSignature or keyEncipherment");
}
}
//
// Check extended key usage.
//
ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.fromExtensions(cert.getExtensions());
if (extendedKeyUsage != null) {
if (!(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth) || extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_msSGC) || extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_nsSGC))) {
throw new CertificateException("Certificate extended key usage must include serverAuth, msSGC or nsSGC");
}
}
} catch (CertificateException c) {
throw c;
} catch (Exception e) {
throw new CertificateException(e.getMessage(), e);
}
}
use of com.google.cloud.security.privateca.v1.KeyUsage in project dcache-cta by dCache.
the class CtaNearlineStorageTest method generateSelfSignedCert.
private void generateSelfSignedCert() throws GeneralSecurityException, OperatorCreationException, IOException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider());
keyPairGenerator.initialize(2048, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
long notBefore = System.currentTimeMillis();
long notAfter = notBefore + TimeUnit.DAYS.toMillis(1);
X500Name subjectDN = new X500Name("CN=localhost, O=dCache.org");
X500Name issuerDN = subjectDN;
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuerDN, BigInteger.ONE, new Date(notBefore), new Date(notAfter), subjectDN, subjectPublicKeyInfo).addExtension(Extension.basicConstraints, true, new BasicConstraints(true)).addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
String signatureAlgorithm = "SHA256WithRSA";
// sign with own key
ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
var cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
try (OutputStream certOut = Files.newOutputStream(certFile.toPath(), CREATE, TRUNCATE_EXISTING, WRITE);
OutputStream keyOut = Files.newOutputStream(keyFile.toPath(), CREATE, TRUNCATE_EXISTING, WRITE)) {
CertificateUtils.saveCertificate(certOut, cert, Encoding.PEM);
CertificateUtils.savePrivateKey(keyOut, keyPair.getPrivate(), Encoding.PEM, null, null);
}
}
Aggregations