use of org.mozilla.jss.netscape.security.x509.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 org.mozilla.jss.netscape.security.x509.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 org.mozilla.jss.netscape.security.x509.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);
}
}
use of org.mozilla.jss.netscape.security.x509.X500Name in project oxAuth by GluuFederation.
the class CertUtils method getCN.
@NotNull
public static String getCN(@Nullable X509Certificate cert) {
try {
if (cert == null) {
return "";
}
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
final RDN[] rdns = x500name.getRDNs(BCStyle.CN);
if (rdns == null || rdns.length == 0) {
return "";
}
RDN cn = rdns[0];
if (cn != null && cn.getFirst() != null && cn.getFirst().getValue() != null) {
return IETFUtils.valueToString(cn.getFirst().getValue());
}
} catch (CertificateEncodingException e) {
log.error(e.getMessage(), e);
}
return "";
}
use of org.mozilla.jss.netscape.security.x509.X500Name in project netty by netty.
the class BouncyCastleSelfSignedCertGenerator method generate.
static String[] generate(String fqdn, KeyPair keypair, SecureRandom random, Date notBefore, Date notAfter, String algorithm) throws Exception {
PrivateKey key = keypair.getPrivate();
// Prepare the information required for generating an X.509 certificate.
X500Name owner = new X500Name("CN=" + fqdn);
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random), notBefore, notAfter, owner, keypair.getPublic());
ContentSigner signer = new JcaContentSignerBuilder(algorithm.equalsIgnoreCase("EC") ? "SHA256withECDSA" : "SHA256WithRSAEncryption").build(key);
X509CertificateHolder certHolder = builder.build(signer);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
cert.verify(keypair.getPublic());
return newSelfSignedCertificate(fqdn, key, cert);
}
Aggregations