use of com.github.zhenwei.core.asn1.x500.X500Name 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 com.github.zhenwei.core.asn1.x500.X500Name in project gitblit by gitblit.
the class X509Utils method newCertificateRevocationList.
/**
* Creates a new certificate revocation list (CRL). This function will
* destroy any existing CRL file.
*
* @param caRevocationList
* @param storeFile
* @param keystorePassword
* @return
*/
public static void newCertificateRevocationList(File caRevocationList, File caKeystoreFile, String caKeystorePassword) {
try {
// read the Gitblit CA key and certificate
KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
X509Certificate caCert = (X509Certificate) store.getCertificate(CA_ALIAS);
X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
// build and sign CRL with CA private key
ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
X509CRLHolder crl = crlBuilder.build(signer);
File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tmpFile);
fos.write(crl.getEncoded());
fos.flush();
fos.close();
if (caRevocationList.exists()) {
caRevocationList.delete();
}
tmpFile.renameTo(caRevocationList);
} finally {
if (fos != null) {
fos.close();
}
if (tmpFile.exists()) {
tmpFile.delete();
}
}
} catch (Exception e) {
throw new RuntimeException("Failed to create new certificate revocation list " + caRevocationList, e);
}
}
use of com.github.zhenwei.core.asn1.x500.X500Name in project gitblit by gitblit.
the class X509Utils method revoke.
/**
* Revoke a certificate.
*
* @param cert
* @param reason
* @param caRevocationList
* @param caPrivateKey
* @param x509log
* @return true if the certificate has been revoked
*/
public static boolean revoke(X509Certificate cert, RevocationReason reason, File caRevocationList, PrivateKey caPrivateKey, X509Log x509log) {
try {
X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(cert).getName());
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
if (caRevocationList.exists()) {
byte[] data = FileUtils.readContent(caRevocationList);
X509CRLHolder crl = new X509CRLHolder(data);
crlBuilder.addCRL(crl);
}
crlBuilder.addCRLEntry(cert.getSerialNumber(), new Date(), reason.ordinal());
// build and sign CRL with CA private key
ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey);
X509CRLHolder crl = crlBuilder.build(signer);
File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tmpFile);
fos.write(crl.getEncoded());
fos.flush();
fos.close();
if (caRevocationList.exists()) {
caRevocationList.delete();
}
tmpFile.renameTo(caRevocationList);
} finally {
if (fos != null) {
fos.close();
}
if (tmpFile.exists()) {
tmpFile.delete();
}
}
x509log.log(MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]", cert.getSerialNumber(), reason.toString(), cert.getSubjectDN().getName()));
return true;
} catch (IOException | OperatorCreationException | CertificateEncodingException e) {
logger.error(MessageFormat.format("Failed to revoke certificate {0,number,0} [{1}] in {2}", cert.getSerialNumber(), cert.getSubjectDN().getName(), caRevocationList));
}
return false;
}
use of com.github.zhenwei.core.asn1.x500.X500Name in project oxAuth by GluuFederation.
the class RSAKeyFactory method generateV3Certificate.
public Certificate generateV3Certificate(Date startDate, Date expirationDate, String dnName) throws OperatorCreationException, CertificateException, CertIOException {
// serial number for certificate
BigInteger serialNumber = new BigInteger(1024, new SecureRandom());
X500Name name = new X500Name(dnName);
JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(name, serialNumber, startDate, expirationDate, name, keyPair.getPublic());
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern();
certGen.addExtension(extendedKeyUsage, false, new DERSequence(purposes));
X509CertificateHolder certHolder = certGen.build(new JcaContentSignerBuilder(signatureAlgorithm.getAlgorithm()).setProvider(SecurityProviderUtility.getBCProviderName()).build(keyPair.getPrivate()));
X509Certificate x509Certificate = new JcaX509CertificateConverter().setProvider(SecurityProviderUtility.getBCProviderName()).getCertificate(certHolder);
return new Certificate(signatureAlgorithm, x509Certificate);
}
use of com.github.zhenwei.core.asn1.x500.X500Name 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);
}
}
Aggregations