use of com.github.zhenwei.core.asn1.x509.Certificate in project Openfire by igniterealtime.
the class CertificateManagerTest method testServerIdentitiesDNS.
/**
* {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
* <ul>
* <li>the DNS subjectAltName value</li>
* <li>explicitly not the Common Name</li>
* </ul>
*
* when a certificate contains:
* <ul>
* <li>a subjectAltName entry of type DNS </li>
* </ul>
*/
@Test
public void testServerIdentitiesDNS() throws Exception {
// Setup fixture.
final String subjectCommonName = "MySubjectCommonName";
final String subjectAltNameDNS = "MySubjectAltNameDNS";
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// Issuer
new X500Name("CN=MyIssuer"), // Random serial number
BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), // Not before 30 days ago
new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30)), // Not after 99 days from now
new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99)), // Subject
new X500Name("CN=" + subjectCommonName), subjectKeyPair.getPublic());
final GeneralNames generalNames = new GeneralNames(new GeneralName(GeneralName.dNSName, subjectAltNameDNS));
builder.addExtension(Extension.subjectAlternativeName, false, generalNames);
final X509CertificateHolder certificateHolder = builder.build(contentSigner);
final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
// Execute system under test
final List<String> serverIdentities = CertificateManager.getServerIdentities(cert);
// Verify result
assertEquals(1, serverIdentities.size());
assertTrue(serverIdentities.contains(subjectAltNameDNS));
assertFalse(serverIdentities.contains(subjectCommonName));
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project Openfire by igniterealtime.
the class CertificateManagerTest method testServerIdentitiesXmppAddr.
/**
* {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
* <ul>
* <li>the 'xmppAddr' subjectAltName value</li>
* <li>explicitly not the Common Name</li>
* </ul>
*
* when a certificate contains:
* <ul>
* <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
* </ul>
*/
@Test
public void testServerIdentitiesXmppAddr() throws Exception {
// Setup fixture.
final String subjectCommonName = "MySubjectCommonName";
final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// Issuer
new X500Name("CN=MyIssuer"), // Random serial number
BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), // Not before 30 days ago
new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30)), // Not after 99 days from now
new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99)), // Subject
new X500Name("CN=" + subjectCommonName), subjectKeyPair.getPublic());
final DERSequence otherName = new DERSequence(new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String(subjectAltNameXmppAddr) });
final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, otherName));
builder.addExtension(Extension.subjectAlternativeName, true, subjectAltNames);
final X509CertificateHolder certificateHolder = builder.build(contentSigner);
final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
// Execute system under test
final List<String> serverIdentities = CertificateManager.getServerIdentities(cert);
// Verify result
assertEquals(1, serverIdentities.size());
assertTrue(serverIdentities.contains(subjectAltNameXmppAddr));
assertFalse(serverIdentities.contains(subjectCommonName));
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project Openfire by igniterealtime.
the class CertificateManager method createSigningRequest.
/**
* Creates and returns the content of a new singing request for the specified certificate. Signing
* requests are required by Certificate Authorities as part of their signing process. The signing request
* contains information about the certificate issuer, subject DN, subject alternative names and public key.
* Private keys are not included. After the Certificate Authority verified and signed the certificate a new
* certificate is going to be returned.
*
* @param cert the certificate to create a signing request.
* @param privKey the private key of the certificate.
* @return the content of a new singing request for the specified certificate.
* @throws OperatorCreationException if there was a problem creating the CSR
* @throws IOException if there was a problem creating the CSR
* @throws CertificateParsingException if there was a problem creating the CSR
*/
public static String createSigningRequest(X509Certificate cert, PrivateKey privKey) throws OperatorCreationException, IOException, CertificateParsingException {
JcaPKCS10CertificationRequestBuilder csrBuilder = new //
JcaPKCS10CertificationRequestBuilder(//
cert.getSubjectX500Principal(), //
cert.getPublicKey());
// Add SubjectAlternativeNames (SANs)
final ASN1EncodableVector subjectAlternativeNames = new ASN1EncodableVector();
final Collection<List<?>> certSans = cert.getSubjectAlternativeNames();
if (certSans != null) {
for (final List<?> certSan : certSans) {
final int nameType = (Integer) certSan.get(0);
// this is either a string, or a byte-array that represents the ASN.1 DER encoded form.
final Object value = certSan.get(1);
switch(nameType) {
case 0:
// OtherName: search for "id-on-xmppAddr" or 'sRVName' or 'userPrincipalName'
try (final ASN1InputStream decoder = new ASN1InputStream((byte[]) value)) {
// By specification, OtherName instances must always be an ASN.1 Sequence.
final ASN1Primitive object = decoder.readObject();
final ASN1Sequence otherNameSeq = (ASN1Sequence) object;
// By specification, an OtherName instance consists of:
// - the type-id (which is an Object Identifier), followed by:
// - a tagged value, of which the tag number is 0 (zero) and the value is defined by the type-id.
final ASN1ObjectIdentifier typeId = (ASN1ObjectIdentifier) otherNameSeq.getObjectAt(0);
final ASN1TaggedObject taggedValue = (ASN1TaggedObject) otherNameSeq.getObjectAt(1);
final int tagNo = taggedValue.getTagNo();
if (tagNo != 0) {
throw new IllegalArgumentException("subjectAltName 'otherName' sequence's second object is expected to be a tagged value of which the tag number is 0. The tag number that was detected: " + tagNo);
}
subjectAlternativeNames.add(new DERTaggedObject(false, GeneralName.otherName, new DERSequence(new ASN1Encodable[] { typeId, taggedValue })));
} catch (Exception e) {
Log.warn("Unable to parse certificate SAN 'otherName' value", e);
}
break;
case 2:
// DNS
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, (String) value));
break;
case 6:
// URI
subjectAlternativeNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, (String) value));
break;
default:
// Not applicable to XMPP, so silently ignore them
break;
}
}
}
final GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(subjectAlternativeNames));
final ExtensionsGenerator extGen = new ExtensionsGenerator();
extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
String signatureAlgorithm = "SHA256WITH" + cert.getPublicKey().getAlgorithm();
ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey);
PKCS10CertificationRequest csr = csrBuilder.build(signer);
StringWriter string = new StringWriter();
PemWriter pemWriter = new PemWriter(string);
PemObjectGenerator objGen = new MiscPEMGenerator(csr);
pemWriter.writeObject(objGen);
pemWriter.close();
return string.toString();
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project indy by Commonjava.
the class CertUtils method createSignedCertificate.
/**
* Generate X509Certificate using objects from existing issuer and subject certificates.
* The generated certificate is signed by issuer PrivateKey.
* @param certificate
* @param issuerCertificate
* @param issuerPrivateKey
* @param isIntermediate
* @return
* @throws Exception
*/
public static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean isIntermediate) throws Exception {
String issuerSigAlg = issuerCertificate.getSigAlgName();
X500Principal principal = issuerCertificate.getIssuerX500Principal();
JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(issuerSigAlg).setProvider(BouncyCastleProvider.PROVIDER_NAME);
JcaX509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(principal, certificate.getSerialNumber(), certificate.getNotBefore(), certificate.getNotAfter(), certificate.getSubjectX500Principal(), certificate.getPublicKey());
if (isIntermediate) {
v3CertGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(-1));
}
return converter.getCertificate(v3CertGen.build(contentSignerBuilder.build(issuerPrivateKey)));
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project neo4j by neo4j.
the class SelfSignedCertificateFactory method createSelfSignedCertificate.
public void createSelfSignedCertificate(Path certificatePath, Path 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());
// Subject alternative name (part of SNI extension, used for hostname verification)
GeneralNames subjectAlternativeName = new GeneralNames(new GeneralName(GeneralName.dNSName, hostName));
builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeName);
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