use of sun.security.x509.X500Name in project Bytecoder by mirkosertic.
the class Builder method targetDistance.
/**
* Determine how close a given certificate gets you toward
* a given target.
*
* @param constraints Current NameConstraints; if null,
* then caller must verify NameConstraints
* independently, realizing that this certificate
* may not actually lead to the target at all.
* @param cert Candidate certificate for chain
* @param target GeneralNameInterface name of target
* @return distance from this certificate to target:
* <ul>
* <li>-1 means certificate could be CA for target, but
* there are no NameConstraints limiting how close
* <li> 0 means certificate subject or subjectAltName
* matches target
* <li> 1 means certificate is permitted to be CA for
* target.
* <li> 2 means certificate is permitted to be CA for
* parent of target.
* <li>>0 in general, means certificate is permitted
* to be a CA for this distance higher in the naming
* hierarchy than the target, plus 1.
* </ul>
* <p>Note that the subject and/or subjectAltName of the
* candidate cert does not have to be an ancestor of the
* target in order to be a CA that can issue a certificate to
* the target. In these cases, the target distance is calculated
* by inspecting the NameConstraints extension in the candidate
* certificate. For example, suppose the target is an X.500 DN with
* a value of "CN=mullan,OU=ireland,O=sun,C=us" and the
* NameConstraints extension in the candidate certificate
* includes a permitted component of "O=sun,C=us", which implies
* that the candidate certificate is allowed to issue certs in
* the "O=sun,C=us" namespace. The target distance is 3
* ((distance of permitted NC from target) + 1).
* The (+1) is added to distinguish the result from the case
* which returns (0).
* @throws IOException if certificate does not get closer
*/
static int targetDistance(NameConstraintsExtension constraints, X509Certificate cert, GeneralNameInterface target) throws IOException {
/* ensure that certificate satisfies existing name constraints */
if (constraints != null && !constraints.verify(cert)) {
throw new IOException("certificate does not satisfy existing name " + "constraints");
}
X509CertImpl certImpl;
try {
certImpl = X509CertImpl.toImpl(cert);
} catch (CertificateException e) {
throw new IOException("Invalid certificate", e);
}
/* see if certificate subject matches target */
X500Name subject = X500Name.asX500Name(certImpl.getSubjectX500Principal());
if (subject.equals(target)) {
/* match! */
return 0;
}
SubjectAlternativeNameExtension altNameExt = certImpl.getSubjectAlternativeNameExtension();
if (altNameExt != null) {
GeneralNames altNames = altNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
/* see if any alternative name matches target */
if (altNames != null) {
for (int j = 0, n = altNames.size(); j < n; j++) {
GeneralNameInterface altName = altNames.get(j).getName();
if (altName.equals(target)) {
return 0;
}
}
}
}
/* no exact match; see if certificate can get us to target */
/* first, get NameConstraints out of certificate */
NameConstraintsExtension ncExt = certImpl.getNameConstraintsExtension();
if (ncExt == null) {
return -1;
}
/* merge certificate's NameConstraints with current NameConstraints */
if (constraints != null) {
constraints.merge(ncExt);
} else {
// Make sure we do a clone here, because we're probably
// going to modify this object later and we don't want to
// be sharing it with a Certificate object!
constraints = (NameConstraintsExtension) ncExt.clone();
}
if (debug != null) {
debug.println("Builder.targetDistance() merged constraints: " + String.valueOf(constraints));
}
/* reduce permitted by excluded */
GeneralSubtrees permitted = constraints.get(NameConstraintsExtension.PERMITTED_SUBTREES);
GeneralSubtrees excluded = constraints.get(NameConstraintsExtension.EXCLUDED_SUBTREES);
if (permitted != null) {
permitted.reduce(excluded);
}
if (debug != null) {
debug.println("Builder.targetDistance() reduced constraints: " + permitted);
}
/* see if new merged constraints allow target */
if (!constraints.verify(target)) {
throw new IOException("New certificate not allowed to sign " + "certificate for target");
}
/* find distance to target, if any, in permitted */
if (permitted == null) {
/* certificate is unconstrained; could sign for anything */
return -1;
}
for (int i = 0, n = permitted.size(); i < n; i++) {
GeneralNameInterface perName = permitted.get(i).getName().getName();
int distance = distance(perName, target, -1);
if (distance >= 0) {
return (distance + 1);
}
}
/* no matching type in permitted; cert holder could certify target */
return -1;
}
use of sun.security.x509.X500Name in project Bytecoder by mirkosertic.
the class PKCS7 method populateCertIssuerNames.
/**
* Populate array of Issuer DNs from certificates and convert
* each Principal to type X500Name if necessary.
*/
private void populateCertIssuerNames() {
if (certificates == null)
return;
certIssuerNames = new Principal[certificates.length];
for (int i = 0; i < certificates.length; i++) {
X509Certificate cert = certificates[i];
Principal certIssuerName = cert.getIssuerDN();
if (!(certIssuerName instanceof X500Name)) {
// types of String attribute values to be changed)
try {
X509CertInfo tbsCert = new X509CertInfo(cert.getTBSCertificate());
certIssuerName = (Principal) tbsCert.get(X509CertInfo.ISSUER + "." + X509CertInfo.DN_NAME);
} catch (Exception e) {
// error generating X500Name object from the cert's
// issuer DN, leave name as is.
}
}
certIssuerNames[i] = certIssuerName;
}
}
use of sun.security.x509.X500Name in project Bytecoder by mirkosertic.
the class VerifierWrapper method getServername.
/*
* Extract the name of the SSL server from the certificate.
*
* Note this code is essentially a subset of the hostname extraction
* code in HostnameChecker.
*/
private static String getServername(X509Certificate peerCert) {
try {
// compare to subjectAltNames if dnsName is present
Collection<List<?>> subjAltNames = peerCert.getSubjectAlternativeNames();
if (subjAltNames != null) {
for (Iterator<List<?>> itr = subjAltNames.iterator(); itr.hasNext(); ) {
List<?> next = itr.next();
if (((Integer) next.get(0)).intValue() == 2) {
// compare dNSName with host in url
String dnsName = ((String) next.get(1));
return dnsName;
}
}
}
// else check against common name in the subject field
X500Name subject = HostnameChecker.getSubjectX500Name(peerCert);
DerValue derValue = subject.findMostSpecificAttribute(X500Name.commonName_oid);
if (derValue != null) {
try {
String name = derValue.getAsString();
return name;
} catch (IOException e) {
// ignore
}
}
} catch (java.security.cert.CertificateException e) {
// ignore
}
return null;
}
use of sun.security.x509.X500Name in project syncope by apache.
the class SAML2ITCase method createKeystores.
private static void createKeystores() throws Exception {
// Create KeyPair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Date currentDate = new Date();
Date expiryDate = new Date(currentDate.getTime() + 365L * 24L * 60L * 60L * 1000L);
// Create X509Certificate
String issuerName = "CN=Issuer";
String subjectName = "CN=Subject";
BigInteger serial = new BigInteger("123456");
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(RFC4519Style.INSTANCE, issuerName), serial, currentDate, expiryDate, new X500Name(RFC4519Style.INSTANCE, subjectName), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
// Store Private Key + Certificate in Keystore
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null, "security".toCharArray());
keystore.setKeyEntry("subject", keyPair.getPrivate(), "security".toCharArray(), new Certificate[] { certificate });
File keystoreFile = File.createTempFile("samlkeystore", ".jks");
try (OutputStream output = Files.newOutputStream(keystoreFile.toPath())) {
keystore.store(output, "security".toCharArray());
}
keystorePath = keystoreFile.toPath();
// Now store the Certificate in the truststore
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, "security".toCharArray());
trustStore.setCertificateEntry("subject", certificate);
File truststoreFile = File.createTempFile("samltruststore", ".jks");
try (OutputStream output = Files.newOutputStream(truststoreFile.toPath())) {
trustStore.store(output, "security".toCharArray());
}
truststorePath = truststoreFile.toPath();
}
use of sun.security.x509.X500Name in project cdap by caskdata.
the class KeyStores method getCertificate.
/**
* Generate an X.509 certificate
*
* @param dn Distinguished name for the owner of the certificate, it will also be the signer of the certificate.
* @param pair Key pair used for signing the certificate.
* @param days Validity of the certificate.
* @param algorithm Name of the signature algorithm used.
* @return A X.509 certificate
*/
private static X509Certificate getCertificate(String dn, KeyPair pair, int days, String algorithm) throws IOException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
// Calculate the validity interval of the certificate
Date from = new Date();
Date to = DateUtils.addDays(from, days);
CertificateValidity interval = new CertificateValidity(from, to);
// Generate a random number to use as the serial number for the certificate
BigInteger sn = new BigInteger(64, new SecureRandom());
// Create the name of the owner based on the provided distinguished name
X500Name owner = new X500Name(dn);
// Create an info objects with the provided information, which will be used to create the certificate
X509CertInfo info = new X509CertInfo();
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
// In java 7, subject is of type CertificateSubjectName and issuer is of type CertificateIssuerName.
// These were changed to X500Name in Java8. So looking at the field type before setting them.
// This certificate will be self signed, hence the subject and the issuer are same.
Field subjectField = null;
try {
subjectField = info.getClass().getDeclaredField("subject");
if (subjectField.getType().equals(X500Name.class)) {
info.set(X509CertInfo.SUBJECT, owner);
info.set(X509CertInfo.ISSUER, owner);
} else {
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
}
} catch (NoSuchFieldException e) {
// Trying to set it to Java 8 types. If one of the underlying fields has changed then this will throw a
// CertificateException which is handled by the caller.
info.set(X509CertInfo.SUBJECT, owner);
info.set(X509CertInfo.ISSUER, owner);
}
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Create the certificate and sign it with the private key
X509CertImpl cert = new X509CertImpl(info);
PrivateKey privateKey = pair.getPrivate();
cert.sign(privateKey, algorithm);
return cert;
}
Aggregations