use of org.bouncycastle.cert.X509v3CertificateBuilder in project platformlayer by platformlayer.
the class SimpleCertificateAuthority method signCertificate.
private static Certificate signCertificate(X500Name signer, PrivateKey signerPrivateKey, X500Name subject, SubjectPublicKeyInfo subjectPublicKeyInfo) throws OpsException {
try {
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(SIGNATURE_ALGORITHM);
AlgorithmIdentifier digestAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
long days = 3650;
long now = System.currentTimeMillis();
Date notBefore = new Date(now - ONE_DAY);
Date notAfter = new Date(notBefore.getTime() + (days * ONE_DAY));
BigInteger serialNumber;
synchronized (SimpleCertificateAuthority.class) {
long nextSerialNumber = System.currentTimeMillis();
serialNumber = BigInteger.valueOf(nextSerialNumber);
}
X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(signer, serialNumber, notBefore, notAfter, subject, subjectPublicKeyInfo);
// {
// boolean isCritical = false;
// certificateBuilder.addExtension(X509Extensions.SubjectKeyIdentifier, isCritical,
// csr.getSubjectPublicKeyInfo());
// }
AsymmetricKeyParameter caPrivateKeyParameters = PrivateKeyFactory.createKey(signerPrivateKey.getEncoded());
ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digestAlgId).build(caPrivateKeyParameters);
X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
Certificate certificate = certificateHolder.toASN1Structure();
return certificate;
} catch (OperatorCreationException e) {
throw new OpsException("Error signing certificate", e);
} catch (IOException e) {
throw new OpsException("Error signing certificate", e);
}
}
use of org.bouncycastle.cert.X509v3CertificateBuilder in project syncany by syncany.
the class CipherUtil method generateSelfSignedCertificate.
/**
* Generates a self-signed certificate, given a public/private key pair.
*
* @see <a href="https://code.google.com/p/gitblit/source/browse/src/com/gitblit/MakeCertificate.java?r=88598bb2f779b73479512d818c675dea8fa72138">Original source of this method</a>
*/
public static X509Certificate generateSelfSignedCertificate(String commonName, KeyPair keyPair) throws OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
// Certificate CN, O and OU
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
builder.addRDN(BCStyle.CN, commonName);
builder.addRDN(BCStyle.O, CipherParams.CERTIFICATE_ORGANIZATION);
builder.addRDN(BCStyle.OU, CipherParams.CERTIFICATE_ORGUNIT);
// Dates and serial
Date notBefore = new Date(System.currentTimeMillis() - 1 * 24 * 60 * 60 * 1000L);
Date notAfter = new Date(System.currentTimeMillis() + 5 * 365 * 24 * 60 * 60 * 1000L);
BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
// Issuer and subject (identical, because self-signed)
X500Name issuer = builder.build();
X500Name subject = issuer;
X509v3CertificateBuilder certificateGenerator = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, keyPair.getPublic());
ContentSigner signatureGenerator = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(CipherParams.CRYPTO_PROVIDER).build(keyPair.getPrivate());
X509Certificate certificate = new JcaX509CertificateConverter().setProvider(CipherParams.CRYPTO_PROVIDER).getCertificate(certificateGenerator.build(signatureGenerator));
certificate.checkValidity(new Date());
certificate.verify(certificate.getPublicKey());
return certificate;
}
use of org.bouncycastle.cert.X509v3CertificateBuilder in project gitblit by gitblit.
the class X509Utils method newClientCertificate.
/**
* Creates a new client certificate PKCS#12 and PEM store. Any existing
* stores are destroyed.
*
* @param clientMetadata a container for dynamic parameters needed for generation
* @param caKeystoreFile
* @param caKeystorePassword
* @param targetFolder
* @return
*/
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
try {
KeyPair pair = newKeyPair();
X500Name userDN = buildDistinguishedName(clientMetadata);
X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
// create a new certificate signed by the Gitblit CA certificate
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore, clientMetadata.notAfter, userDN, pair.getPublic());
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
if (!StringUtils.isEmpty(clientMetadata.emailAddress)) {
GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
}
ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
// confirm the validity of the user certificate
userCert.checkValidity();
userCert.verify(caCert.getPublicKey());
userCert.getIssuerDN().equals(caCert.getSubjectDN());
// verify user certificate chain
verifyChain(userCert, caCert);
targetFolder.mkdirs();
// save certificate, stamped with unique name
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
String id = date;
File certFile = new File(targetFolder, id + ".cer");
int count = 0;
while (certFile.exists()) {
id = date + "_" + Character.toString((char) (0x61 + count));
certFile = new File(targetFolder, id + ".cer");
count++;
}
// save user private key, user certificate and CA certificate to a PKCS#12 store
File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
if (p12File.exists()) {
p12File.delete();
}
KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
userStore.setKeyEntry(MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[] { userCert });
userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
saveKeyStore(p12File, userStore, clientMetadata.password);
// save user private key, user certificate, and CA certificate to a PEM store
File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
if (pemFile.exists()) {
pemFile.delete();
}
JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
builder.setSecureRandom(new SecureRandom());
PEMEncryptor pemEncryptor = builder.build(clientMetadata.password.toCharArray());
JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(pemFile));
pemWriter.writeObject(pair.getPrivate(), pemEncryptor);
pemWriter.writeObject(userCert);
pemWriter.writeObject(caCert);
pemWriter.flush();
pemWriter.close();
// save certificate after successfully creating the key stores
saveCertificate(userCert, certFile);
// update serial number in metadata object
clientMetadata.serialNumber = userCert.getSerialNumber().toString();
return userCert;
} catch (Throwable t) {
throw new RuntimeException("Failed to generate client certificate!", t);
}
}
use of org.bouncycastle.cert.X509v3CertificateBuilder in project gitblit by gitblit.
the class X509Utils method newSSLCertificate.
/**
* Creates a new SSL certificate signed by the CA private key and stored in
* keyStore.
*
* @param sslMetadata
* @param caPrivateKey
* @param caCert
* @param targetStoreFile
* @param x509log
*/
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) {
try {
KeyPair pair = newKeyPair();
X500Name webDN = buildDistinguishedName(sslMetadata);
X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter, webDN, pair.getPublic());
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
// support alternateSubjectNames for SSL certificates
List<GeneralName> altNames = new ArrayList<GeneralName>();
if (HttpUtils.isIpAddress(sslMetadata.commonName)) {
altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
}
if (altNames.size() > 0) {
GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
}
ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(caSigner));
cert.checkValidity(new Date());
cert.verify(caCert.getPublicKey());
// Save to keystore
KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(), new Certificate[] { cert, caCert });
saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);
x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));
// update serial number in metadata object
sslMetadata.serialNumber = cert.getSerialNumber().toString();
return cert;
} catch (Throwable t) {
throw new RuntimeException("Failed to generate SSL certificate!", t);
}
}
use of org.bouncycastle.cert.X509v3CertificateBuilder in project gitblit by gitblit.
the class X509Utils method newCertificateAuthority.
/**
* Creates a new certificate authority PKCS#12 store. This function will
* destroy any existing CA store.
*
* @param metadata
* @param storeFile
* @param keystorePassword
* @param x509log
* @return
*/
public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
try {
KeyPair caPair = newKeyPair();
ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());
// clone metadata
X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
X500Name issuerDN = buildDistinguishedName(caMetadata);
// Generate self-signed certificate
X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), caMetadata.notBefore, caMetadata.notAfter, issuerDN, caPair.getPublic());
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));
// confirm the validity of the CA certificate
cert.checkValidity(new Date());
cert.verify(cert.getPublicKey());
// Delete existing keystore
if (storeFile.exists()) {
storeFile.delete();
}
// Save private key and certificate to new keystore
KeyStore store = openKeyStore(storeFile, caMetadata.password);
store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(), new Certificate[] { cert });
saveKeyStore(storeFile, store, caMetadata.password);
x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));
// update serial number in metadata object
caMetadata.serialNumber = cert.getSerialNumber().toString();
return cert;
} catch (Throwable t) {
throw new RuntimeException("Failed to generate Gitblit CA certificate!", t);
}
}
Aggregations