use of org.openecard.bouncycastle.asn1.x509.Certificate in project nhin-d by DirectProject.
the class CertGenerator method createLeafCertificate.
private static CertCreateFields createLeafCertificate(CertCreateFields fields, KeyPair keyPair) throws Exception {
StringBuilder dnBuilder = new StringBuilder();
// create the DN
if (fields.getAttributes().containsKey("EMAILADDRESS"))
dnBuilder.append("EMAILADDRESS=").append(fields.getAttributes().get("EMAILADDRESS")).append(", ");
if (fields.getAttributes().containsKey("CN"))
dnBuilder.append("CN=").append(fields.getAttributes().get("CN")).append(", ");
if (fields.getAttributes().containsKey("C"))
dnBuilder.append("C=").append(fields.getAttributes().get("C")).append(", ");
if (fields.getAttributes().containsKey("ST"))
dnBuilder.append("ST=").append(fields.getAttributes().get("ST")).append(", ");
if (fields.getAttributes().containsKey("L"))
dnBuilder.append("L=").append(fields.getAttributes().get("L")).append(", ");
if (fields.getAttributes().containsKey("O"))
dnBuilder.append("O=").append(fields.getAttributes().get("O")).append(", ");
String DN = dnBuilder.toString().trim();
if (DN.endsWith(","))
;
DN = DN.substring(0, DN.length() - 1);
X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.DAY_OF_MONTH, fields.getExpDays());
// not the best way to do this... generally done with a db file
v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
// issuer is the parent cert
v1CertGen.setIssuerDN(fields.getSignerCert().getSubjectX500Principal());
v1CertGen.setNotBefore(start.getTime());
v1CertGen.setNotAfter(end.getTime());
v1CertGen.setSubjectDN(new X509Principal(DN));
v1CertGen.setPublicKey(keyPair.getPublic());
v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
// pointer to the parent CA
v1CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(fields.getSignerCert()));
v1CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
v1CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
// use the CA's private key to sign the certificate
X509Certificate newCACert = v1CertGen.generate((PrivateKey) fields.getSignerKey(), "BC");
// validate the certificate
newCACert.verify(fields.getSignerCert().getPublicKey());
// write the certificate the file system
writeCertAndKey(newCACert, keyPair.getPrivate(), fields);
return fields;
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project jetty-bootstrap by teknux-org.
the class JettyKeystoreGeneratorBuilder method generateCertificate.
private static Certificate generateCertificate(KeyPair keyPair, String domainName, String signatureAlgorithm, String rdnOuValue, String rdnOValue, int dateNotBeforeNumberOfDays, int dateNotAfterNumberOfDays) throws JettyKeystoreException {
X500NameBuilder issuerX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
if (rdnOuValue != null) {
issuerX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
}
if (rdnOValue != null) {
issuerX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
}
X500Name issuer = issuerX500Namebuilder.addRDN(BCStyle.CN, domainName).build();
BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
Date dateNotBefore = new Date(System.currentTimeMillis() - (dateNotBeforeNumberOfDays * DAY_IN_MILLIS));
Date dateNotAfter = new Date(System.currentTimeMillis() + (dateNotAfterNumberOfDays * DAY_IN_MILLIS));
X500NameBuilder subjectX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
if (rdnOuValue != null) {
subjectX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
}
if (rdnOValue != null) {
subjectX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
}
X500Name subject = subjectX500Namebuilder.addRDN(BCStyle.CN, domainName).build();
SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial, dateNotBefore, dateNotAfter, subject, publicKeyInfo);
Provider provider = new BouncyCastleProvider();
try {
ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(keyPair.getPrivate());
return new JcaX509CertificateConverter().setProvider(provider).getCertificate(x509v3CertificateBuilder.build(signer));
} catch (OperatorCreationException | CertificateException e) {
throw new JettyKeystoreException(JettyKeystoreException.ERROR_CREATE_CERTIFICATE, "Can not generate certificate", e);
}
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project athenz by yahoo.
the class ZTSClient method getAWSLambdaServiceCertificate.
/**
* For AWS Lambda functions generate a new private key, request a
* x.509 certificate based on the requested CSR and return both to
* the client in order to establish tls connections with other
* Athenz enabled services.
* @param domainName name of the domain
* @param serviceName name of the service
* @param account AWS account name that the function runs in
* @param provider name of the provider service for AWS Lambda
* @return AWSLambdaIdentity with private key and certificate
*/
public AWSLambdaIdentity getAWSLambdaServiceCertificate(String domainName, String serviceName, String account, String provider) {
if (domainName == null || serviceName == null) {
throw new IllegalArgumentException("Domain and Service must be specified");
}
if (account == null || provider == null) {
throw new IllegalArgumentException("AWS Account and Provider must be specified");
}
if (x509CsrDomain == null) {
throw new IllegalArgumentException("X509 CSR Domain must be specified");
}
// first we're going to generate a private key for the request
AWSLambdaIdentity lambdaIdentity = new AWSLambdaIdentity();
try {
lambdaIdentity.setPrivateKey(Crypto.generateRSAPrivateKey(2048));
} catch (CryptoException ex) {
throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
}
// we need to generate an csr with an instance register object
InstanceRegisterInformation info = new InstanceRegisterInformation();
info.setDomain(domainName.toLowerCase());
info.setService(serviceName.toLowerCase());
info.setProvider(provider.toLowerCase());
final String athenzService = info.getDomain() + "." + info.getService();
// generate our dn which will be based on our service name
StringBuilder dnBuilder = new StringBuilder(128);
dnBuilder.append("cn=");
dnBuilder.append(athenzService);
if (x509CsrDn != null) {
dnBuilder.append(',');
dnBuilder.append(x509CsrDn);
}
// now let's generate our dsnName field based on our principal's details
StringBuilder hostBuilder = new StringBuilder(128);
hostBuilder.append(info.getService());
hostBuilder.append('.');
hostBuilder.append(info.getDomain().replace('.', '-'));
hostBuilder.append('.');
hostBuilder.append(x509CsrDomain);
StringBuilder instanceHostBuilder = new StringBuilder(128);
instanceHostBuilder.append("lambda-");
instanceHostBuilder.append(account);
instanceHostBuilder.append('-');
instanceHostBuilder.append(info.getService());
instanceHostBuilder.append(".instanceid.athenz.");
instanceHostBuilder.append(x509CsrDomain);
GeneralName[] sanArray = new GeneralName[2];
sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostBuilder.toString()));
sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(instanceHostBuilder.toString()));
try {
info.setCsr(Crypto.generateX509CSR(lambdaIdentity.getPrivateKey(), dnBuilder.toString(), sanArray));
} catch (OperatorCreationException | IOException ex) {
throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
}
// finally obtain attestation data for lambda
info.setAttestationData(getAWSLambdaAttestationData(athenzService, account));
// request the x.509 certificate from zts server
Map<String, List<String>> responseHeaders = new HashMap<>();
InstanceIdentity identity = postInstanceRegisterInformation(info, responseHeaders);
try {
lambdaIdentity.setX509Certificate(Crypto.loadX509Certificate(identity.getX509Certificate()));
} catch (CryptoException ex) {
throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
}
return lambdaIdentity;
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project fdroidclient by f-droid.
the class LocalRepoKeyStore method generateSelfSignedCertChain.
private Certificate generateSelfSignedCertChain(KeyPair kp, X500Name subject, String hostname) throws CertificateException, OperatorCreationException, IOException {
SecureRandom rand = new SecureRandom();
PrivateKey privKey = kp.getPrivate();
PublicKey pubKey = kp.getPublic();
ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);
SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(pubKey.getEncoded()));
// now
Date now = new Date();
/* force it to use a English/Gregorian dates for the cert, hardly anyone
ever looks at the cert metadata anyway, and its very likely that they
understand English/Gregorian dates */
Calendar c = new GregorianCalendar(Locale.ENGLISH);
c.setTime(now);
c.add(Calendar.YEAR, 1);
Time startTime = new Time(now, Locale.ENGLISH);
Time endTime = new Time(c.getTime(), Locale.ENGLISH);
X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(subject, BigInteger.valueOf(rand.nextLong()), startTime, endTime, subject, subPubKeyInfo);
if (hostname != null) {
GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.iPAddress, hostname));
v3CertGen.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
}
X509CertificateHolder certHolder = v3CertGen.build(sigGen);
return new JcaX509CertificateConverter().getCertificate(certHolder);
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project pac4j by pac4j.
the class SAML2ClientConfiguration method createKeystore.
private void createKeystore() {
try {
if (CommonHelper.isBlank(this.keyStoreAlias)) {
this.keyStoreAlias = getClass().getSimpleName();
LOGGER.warn("Using keystore alias {}", this.keyStoreAlias);
}
if (CommonHelper.isBlank(this.keyStoreType)) {
this.keyStoreType = KeyStore.getDefaultType();
LOGGER.warn("Using keystore type {}", this.keyStoreType);
}
final KeyStore ks = KeyStore.getInstance(this.keyStoreType);
final char[] password = this.keystorePassword.toCharArray();
ks.load(null, password);
final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
final KeyPair kp = kpg.genKeyPair();
final String sigAlgName = "SHA1WithRSA";
final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
final String dn = InetAddress.getLocalHost().getHostName();
final PrivateKey signingKey = kp.getPrivate();
final X509Certificate certificate = createSelfSignedCert(new X500Name("CN=" + dn), sigAlgName, sigAlgID, kp);
final char[] keyPassword = this.privateKeyPassword.toCharArray();
ks.setKeyEntry(this.keyStoreAlias, signingKey, keyPassword, new Certificate[] { certificate });
try (final FileOutputStream fos = new FileOutputStream(this.keystoreResource.getFile().getCanonicalPath())) {
ks.store(fos, password);
fos.flush();
}
LOGGER.info("Created keystore {} with key alias {} ", keystoreResource.getFile().getCanonicalPath(), ks.aliases().nextElement());
} catch (final Exception e) {
throw new SAMLException("Could not create keystore", e);
}
}
Aggregations