use of org.bouncycastle.asn1.x509.Certificate in project kafka by apache.
the class TestSslUtils method generateCertificate.
/**
* Create a self-signed X.509 Certificate.
* From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
*
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
* @return the self-signed certificate
* @throws CertificateException thrown if a security error or an IO error occurred.
*/
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException {
try {
Security.addProvider(new BouncyCastleProvider());
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
X500Name name = new X500Name(dn);
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000L);
BigInteger sn = new BigInteger(64, new SecureRandom());
X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
} catch (CertificateException ce) {
throw ce;
} catch (Exception e) {
throw new CertificateException(e);
}
}
use of org.bouncycastle.asn1.x509.Certificate in project OpenAttestation by OpenAttestation.
the class CertificateRepository method create.
@Override
public // @RequiresPermissions("tag_certificates:create")
void create(Certificate item) {
log.debug("Certificate:Create - Got request to create a new Certificate {}.", item.getId().toString());
CertificateLocator locator = new CertificateLocator();
locator.id = item.getId();
try (CertificateDAO dao = TagJdbi.certificateDao()) {
Certificate newCert = dao.findById(item.getId());
if (newCert == null) {
newCert = Certificate.valueOf(item.getCertificate());
dao.insert(item.getId(), newCert.getCertificate(), newCert.getSha1().toHexString(), newCert.getSha256().toHexString(), newCert.getSubject(), newCert.getIssuer(), newCert.getNotBefore(), newCert.getNotAfter());
log.debug("Certificate:Create - Created the Certificate {} successfully.", item.getId().toString());
} else {
log.error("Certificate:Create - Certificate {} will not be created since a duplicate Certificate already exists.", item.getId().toString());
throw new RepositoryCreateConflictException(locator);
}
} catch (RepositoryException re) {
throw re;
} catch (Exception ex) {
log.error("Certificate:Create - Error during certificate creation.", ex);
throw new RepositoryCreateException(ex, locator);
}
//Store tag values from Certificate
try {
log.info("Tags from certificate will now be stored");
KvAttributeRepository repository = new KvAttributeRepository();
KvAttribute kvAttrib = new KvAttribute();
if (kvAttrib == null || repository == null)
log.debug("kvAttrib or repository Obj is null, unable to store certificate tags");
else {
List<Attribute> certAttributes = X509AttributeCertificate.valueOf(item.getCertificate()).getAttribute();
for (Attribute attr : certAttributes) {
for (ASN1Encodable value : attr.getAttributeValues()) {
if (attr.getAttrType().toString().equals(UTF8NameValueMicroformat.OID)) {
UTF8NameValueMicroformat microformat = new UTF8NameValueMicroformat(DERUTF8String.getInstance(value));
// Check if that tag with same value already exists
KvAttributeFilterCriteria criteria = new KvAttributeFilterCriteria();
criteria.nameEqualTo = microformat.getName();
criteria.valueEqualTo = microformat.getValue();
KvAttributeCollection results = repository.search(criteria);
if (results.getDocuments().isEmpty()) {
kvAttrib.setId(new UUID());
kvAttrib.setName(microformat.getName());
kvAttrib.setValue(microformat.getValue());
repository.create(kvAttrib);
} else
log.debug("Tag with Name:{} & Value:{} is already stored.", microformat.getName(), microformat.getValue());
}
}
}
}
} catch (Exception e) {
log.error("Certificate:Create - Error during attribute scan", e);
}
}
use of org.bouncycastle.asn1.x509.Certificate in project OpenAttestation by OpenAttestation.
the class ProvisionTagCertificate method certificateAttributesEqual.
//
// /**
// * Check that the attributes in the certificate are the same as the attributes in the given selection.
// * The order is not considered so they do not have to be in the same order.
// *
// * The given selection must have inline attributes (not requiring any lookup by id or name).
// *
// * @return true if the attribute certificate has exactly the same attributes as in the given selection
// */
protected boolean certificateAttributesEqual(X509AttributeCertificate certificate, SelectionType selection) throws IOException {
List<Attribute> certAttributes = certificate.getAttribute();
// initialized with all false, later we mark individual elements true if they are found within the given selection, so that if any are left false at the end we know that there are attributes in the cert that were not in the selection
boolean[] certAttrMatch = new boolean[certAttributes.size()];
// for every attribute in the selection, check if it's present in the certificate
for (AttributeType xmlAttribute : selection.getAttribute()) {
X509AttrBuilder.Attribute oidAndValue = Util.toAttributeOidValue(xmlAttribute);
// look through the certificate for same oid and value
boolean found = false;
for (int i = 0; i < certAttrMatch.length; i++) {
if (Arrays.equals(certAttributes.get(i).getAttrType().getDEREncoded(), oidAndValue.oid.getDEREncoded())) {
if (Arrays.equals(certAttributes.get(i).getAttributeValues()[0].getDEREncoded(), oidAndValue.value.getDEREncoded())) {
certAttrMatch[i] = true;
found = true;
}
}
}
if (!found) {
log.debug("Certificate does not have attribute oid {} and value {}", Hex.encodeHexString(oidAndValue.oid.getDEREncoded()), Hex.encodeHexString(oidAndValue.value.getDEREncoded()));
return false;
}
}
// check if the certificate has any attributes that are not in the selection
for (int i = 0; i < certAttrMatch.length; i++) {
if (!certAttrMatch[i]) {
log.debug("Selection does not have attribute oid {} and value {}", Hex.encodeHexString(certAttributes.get(i).getAttrType().getDEREncoded()), Hex.encodeHexString(certAttributes.get(i).getAttributeValues()[0].getDEREncoded()));
return false;
}
}
// certificate and selection have same set of attribute (oid,value) pairs
return true;
}
use of org.bouncycastle.asn1.x509.Certificate in project Openfire by igniterealtime.
the class CertificateManager method createX509V3Certificate.
/**
* Creates an X509 version3 certificate.
*
* @param kp KeyPair that keeps the public and private keys for the new certificate.
* @param days time to live
* @param issuerBuilder IssuerDN builder
* @param subjectBuilder SubjectDN builder
* @param domain Domain of the server.
* @param signAlgoritm Signature algorithm. This can be either a name or an OID.
* @return X509 V3 Certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
PublicKey pubKey = kp.getPublic();
PrivateKey privKey = kp.getPrivate();
byte[] serno = new byte[8];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed((new Date().getTime()));
random.nextBytes(serno);
BigInteger serial = (new java.math.BigInteger(serno)).abs();
X500Name issuerDN = issuerBuilder.build();
X500Name subjectDN = subjectBuilder.build();
// builder
JcaX509v3CertificateBuilder certBuilder = new //
JcaX509v3CertificateBuilder(//
issuerDN, //
serial, //
new Date(), //
new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
subjectDN, //
pubKey);
// add subjectAlternativeName extension
boolean critical = subjectDN.getRDNs().length == 0;
ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
// add keyIdentifiers extensions
JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
try {
// build the certificate
ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
X509CertificateHolder cert = certBuilder.build(signer);
// verify the validity
if (!cert.isValidOn(new Date())) {
throw new GeneralSecurityException("Certificate validity not valid");
}
// verify the signature (self-signed)
ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
if (!cert.isSignatureValid(verifierProvider)) {
throw new GeneralSecurityException("Certificate signature not valid");
}
return new JcaX509CertificateConverter().getCertificate(cert);
} catch (OperatorCreationException | CertException e) {
throw new GeneralSecurityException(e);
}
}
use of org.bouncycastle.asn1.x509.Certificate in project neo4j by neo4j.
the class Certificates method createSelfSignedCertificate.
public void createSelfSignedCertificate(File certificatePath, File privateKeyPath, String hostName) throws GeneralSecurityException, IOException, OperatorCreationException {
installCleanupHook(certificatePath, privateKeyPath);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ENCRYPTION);
keyGen.initialize(2048, random);
KeyPair keypair = keyGen.generateKeyPair();
// Prepare the information required for generating an X.509 certificate.
X500Name owner = new X500Name("CN=" + hostName);
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic());
PrivateKey privateKey = keypair.getPrivate();
ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").build(privateKey);
X509CertificateHolder certHolder = builder.build(signer);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
//check so that cert is valid
cert.verify(keypair.getPublic());
//write to disk
writePem("CERTIFICATE", cert.getEncoded(), certificatePath);
writePem("PRIVATE KEY", privateKey.getEncoded(), privateKeyPath);
// Mark as done so we don't clean up certificates
cleanupRequired = false;
}
Aggregations