use of org.bouncycastle.asn1.x509.BasicConstraints 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 org.bouncycastle.asn1.x509.BasicConstraints in project Openfire by igniterealtime.
the class KeystoreTestUtils method generateTestCertificate.
private static X509Certificate generateTestCertificate(final boolean isValid, final KeyPair issuerKeyPair, final KeyPair subjectKeyPair, int indexAwayFromEndEntity) throws Exception {
// Issuer and Subject.
final X500Name subject = new X500Name("CN=" + Base64.encodeBytes(subjectKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
final X500Name issuer = new X500Name("CN=" + Base64.encodeBytes(issuerKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
// Validity
final Date notBefore;
final Date notAfter;
if (isValid) {
// 30 days ago
notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30));
// 99 days from now.
notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99));
} else {
// Generate a certificate for which the validate period has expired.
// 40 days ago
notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 40));
// 10 days ago
notAfter = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 10));
}
// The new certificate should get a unique serial number.
final BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, subjectKeyPair.getPublic());
// When this certificate is used to sign another certificate, basic constraints need to be set.
if (indexAwayFromEndEntity > 0) {
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(indexAwayFromEndEntity - 1));
}
final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(issuerKeyPair.getPrivate());
final X509CertificateHolder certificateHolder = builder.build(contentSigner);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
}
use of org.bouncycastle.asn1.x509.BasicConstraints in project zaproxy by zaproxy.
the class SslCertificateServiceImpl method createCertForHost.
@Override
public KeyStore createCertForHost(CertData certData) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
}
CertData.Name[] certDataNames = certData.getSubjectAlternativeNames();
GeneralName[] subjectAlternativeNames = new GeneralName[certDataNames.length];
for (int i = 0; i < certDataNames.length; i++) {
CertData.Name certDataName = certDataNames[i];
subjectAlternativeNames[i] = new GeneralName(certDataName.getType(), certDataName.getValue());
}
if (certData.getCommonName() == null && subjectAlternativeNames.length == 0) {
throw new IllegalArgumentException("commonName is null and no subjectAlternativeNames are specified");
}
final KeyPair mykp = this.createKeyPair();
final PrivateKey privKey = mykp.getPrivate();
final PublicKey pubKey = mykp.getPublic();
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
if (certData.getCommonName() != null) {
namebld.addRDN(BCStyle.CN, certData.getCommonName());
}
namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
namebld.addRDN(BCStyle.O, "OWASP");
namebld.addRDN(BCStyle.C, "xx");
namebld.addRDN(BCStyle.EmailAddress, "zaproxy-develop@googlegroups.com");
long currentTime = System.currentTimeMillis();
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(currentTime - Duration.ofDays(SITE_CERTIFICATE_START_ADJUSTMENT).toMillis()), new Date(currentTime + Duration.ofDays(SITE_CERTIFICATE_END_VALIDITY_PERIOD).toMillis()), namebld.build(), pubKey);
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth }));
if (subjectAlternativeNames.length > 0) {
certGen.addExtension(Extension.subjectAlternativeName, certData.isSubjectAlternativeNameIsCritical(), new GeneralNames(subjectAlternativeNames));
}
ContentSigner sigGen;
try {
sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
} catch (OperatorCreationException e) {
throw new CertificateException(e);
}
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
cert.verify(caPubKey);
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
final Certificate[] chain = new Certificate[2];
chain[1] = this.caCert;
chain[0] = cert;
ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
return ks;
}
use of org.bouncycastle.asn1.x509.BasicConstraints 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 org.bouncycastle.asn1.x509.BasicConstraints in project xipki by xipki.
the class ProfileConfCreatorDemo method certprofileEeComplex.
// method certprofileEeComplex
private static X509ProfileType certprofileEeComplex() throws Exception {
X509ProfileType profile = getBaseProfile("certprofile ee-complex", X509CertLevel.EndEntity, "5y", true);
// Subject
Subject subject = profile.getSubject();
subject.setIncSerialNumber(false);
subject.setKeepRdnOrder(true);
List<RdnType> rdnControls = subject.getRdn();
rdnControls.add(createRdn(ObjectIdentifiers.DN_CN, 1, 1));
rdnControls.add(createRdn(ObjectIdentifiers.DN_C, 1, 1, new String[] { "DE|FR" }, null, null));
rdnControls.add(createRdn(ObjectIdentifiers.DN_O, 1, 1));
rdnControls.add(createRdn(ObjectIdentifiers.DN_OU, 0, 1));
rdnControls.add(createRdn(ObjectIdentifiers.DN_SN, 0, 1, new String[] { REGEX_SN }, null, null));
rdnControls.add(createRdn(ObjectIdentifiers.DN_DATE_OF_BIRTH, 0, 1));
rdnControls.add(createRdn(ObjectIdentifiers.DN_POSTAL_ADDRESS, 0, 1));
rdnControls.add(createRdn(ObjectIdentifiers.DN_UNIQUE_IDENTIFIER, 1, 1));
// Extensions
// Extensions - general
ExtensionsType extensions = profile.getExtensions();
// Extensions - controls
List<ExtensionType> list = extensions.getExtension();
list.add(createExtension(Extension.subjectKeyIdentifier, true, false, null));
list.add(createExtension(Extension.cRLDistributionPoints, false, false, null));
list.add(createExtension(Extension.freshestCRL, false, false, null));
// Extensions - basicConstraints
ExtensionValueType extensionValue = null;
list.add(createExtension(Extension.basicConstraints, true, false, extensionValue));
// Extensions - AuthorityInfoAccess
extensionValue = createAuthorityInfoAccess();
list.add(createExtension(Extension.authorityInfoAccess, true, false, extensionValue));
// Extensions - AuthorityKeyIdentifier
extensionValue = createAuthorityKeyIdentifier(true);
list.add(createExtension(Extension.authorityKeyIdentifier, true, false, extensionValue));
// Extensions - keyUsage
extensionValue = createKeyUsages(new KeyUsageEnum[] { KeyUsageEnum.DIGITAL_SIGNATURE, KeyUsageEnum.DATA_ENCIPHERMENT, KeyUsageEnum.KEY_ENCIPHERMENT }, null);
list.add(createExtension(Extension.keyUsage, true, true, extensionValue));
// Extensions - extenedKeyUsage
extensionValue = createExtendedKeyUsage(new ASN1ObjectIdentifier[] { ObjectIdentifiers.id_kp_serverAuth }, new ASN1ObjectIdentifier[] { ObjectIdentifiers.id_kp_clientAuth });
list.add(createExtension(Extension.extendedKeyUsage, true, false, extensionValue));
// Extension - subjectDirectoryAttributes
SubjectDirectoryAttributs subjectDirAttrType = new SubjectDirectoryAttributs();
List<OidWithDescType> attrTypes = subjectDirAttrType.getType();
attrTypes.add(createOidType(ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP));
attrTypes.add(createOidType(ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE));
attrTypes.add(createOidType(ObjectIdentifiers.DN_GENDER));
attrTypes.add(createOidType(ObjectIdentifiers.DN_DATE_OF_BIRTH));
attrTypes.add(createOidType(ObjectIdentifiers.DN_PLACE_OF_BIRTH));
extensionValue = createExtensionValueType(subjectDirAttrType);
list.add(createExtension(Extension.subjectDirectoryAttributes, true, false, extensionValue));
// Extension - Admission
AdmissionSyntax admissionSyntax = new AdmissionSyntax();
admissionSyntax.setAdmissionAuthority(new GeneralName(new X500Name("C=DE,CN=admissionAuthority level 1")).getEncoded());
AdmissionsType admissions = new AdmissionsType();
admissions.setAdmissionAuthority(new GeneralName(new X500Name("C=DE,CN=admissionAuthority level 2")).getEncoded());
NamingAuthorityType namingAuthorityL2 = new NamingAuthorityType();
namingAuthorityL2.setOid(createOidType(new ASN1ObjectIdentifier("1.2.3.4.5")));
namingAuthorityL2.setUrl("http://naming-authority-level2.example.org");
namingAuthorityL2.setText("namingAuthrityText level 2");
admissions.setNamingAuthority(namingAuthorityL2);
admissionSyntax.getContentsOfAdmissions().add(admissions);
ProfessionInfoType pi = new ProfessionInfoType();
admissions.getProfessionInfo().add(pi);
pi.getProfessionOid().add(createOidType(new ASN1ObjectIdentifier("1.2.3.4"), "demo oid"));
pi.getProfessionItem().add("demo item");
NamingAuthorityType namingAuthorityL3 = new NamingAuthorityType();
namingAuthorityL3.setOid(createOidType(new ASN1ObjectIdentifier("1.2.3.4.5")));
namingAuthorityL3.setUrl("http://naming-authority-level3.example.org");
namingAuthorityL3.setText("namingAuthrityText level 3");
pi.setNamingAuthority(namingAuthorityL3);
pi.setAddProfessionInfo(new byte[] { 1, 2, 3, 4 });
RegistrationNumber regNum = new RegistrationNumber();
pi.setRegistrationNumber(regNum);
regNum.setRegex("a*b");
// check the syntax
XmlX509CertprofileUtil.buildAdmissionSyntax(false, admissionSyntax);
extensionValue = createExtensionValueType(admissionSyntax);
list.add(createExtension(ObjectIdentifiers.id_extension_admission, true, false, extensionValue));
// restriction
extensionValue = createRestriction(DirectoryStringType.UTF_8_STRING, "demo restriction");
list.add(createExtension(ObjectIdentifiers.id_extension_restriction, true, false, extensionValue));
// additionalInformation
extensionValue = createAdditionalInformation(DirectoryStringType.UTF_8_STRING, "demo additional information");
list.add(createExtension(ObjectIdentifiers.id_extension_additionalInformation, true, false, extensionValue));
// validationModel
extensionValue = createConstantExtValue(new ASN1ObjectIdentifier("1.3.6.1.4.1.8301.3.5.1").getEncoded(), "chain");
list.add(createExtension(ObjectIdentifiers.id_extension_validityModel, true, false, extensionValue));
// privateKeyUsagePeriod
extensionValue = createPrivateKeyUsagePeriod("3y");
list.add(createExtension(Extension.privateKeyUsagePeriod, true, false, extensionValue));
// QcStatements
extensionValue = createQcStatements(true);
list.add(createExtension(Extension.qCStatements, true, false, extensionValue));
// biometricInfo
extensionValue = createBiometricInfo();
list.add(createExtension(Extension.biometricInfo, true, false, extensionValue));
// authorizationTemplate
extensionValue = createAuthorizationTemplate();
list.add(createExtension(ObjectIdentifiers.id_xipki_ext_authorizationTemplate, true, false, extensionValue));
// SubjectAltName
SubjectAltName subjectAltNameMode = new SubjectAltName();
OtherName otherName = new OtherName();
otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.1"), "dummy oid 1"));
otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.2"), "dummy oid 2"));
subjectAltNameMode.setOtherName(otherName);
subjectAltNameMode.setRfc822Name("");
subjectAltNameMode.setDnsName("");
subjectAltNameMode.setDirectoryName("");
subjectAltNameMode.setEdiPartyName("");
subjectAltNameMode.setUniformResourceIdentifier("");
subjectAltNameMode.setIpAddress("");
subjectAltNameMode.setRegisteredID("");
extensionValue = createExtensionValueType(subjectAltNameMode);
list.add(createExtension(Extension.subjectAlternativeName, true, false, extensionValue));
// SubjectInfoAccess
List<ASN1ObjectIdentifier> accessMethods = new LinkedList<>();
accessMethods.add(ObjectIdentifiers.id_ad_caRepository);
for (int i = 0; i < 10; i++) {
accessMethods.add(new ASN1ObjectIdentifier("2.3.4." + (i + 1)));
}
SubjectInfoAccess subjectInfoAccessMode = new SubjectInfoAccess();
for (ASN1ObjectIdentifier accessMethod : accessMethods) {
SubjectInfoAccess.Access access = new SubjectInfoAccess.Access();
subjectInfoAccessMode.getAccess().add(access);
access.setAccessMethod(createOidType(accessMethod));
GeneralNameType accessLocation = new GeneralNameType();
access.setAccessLocation(accessLocation);
otherName = new OtherName();
otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.1"), "dummy oid 1"));
otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.2"), "dummy oid 2"));
accessLocation.setOtherName(otherName);
accessLocation.setRfc822Name("");
accessLocation.setDnsName("");
accessLocation.setDirectoryName("");
accessLocation.setEdiPartyName("");
accessLocation.setUniformResourceIdentifier("");
accessLocation.setIpAddress("");
accessLocation.setRegisteredID("");
}
extensionValue = createExtensionValueType(subjectInfoAccessMode);
list.add(createExtension(Extension.subjectInfoAccess, true, false, extensionValue));
return profile;
}
Aggregations