use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project coprhd-controller by CoprHD.
the class KeyCertificatePairGenerator method generateCertificate.
/**
* Create a self-signed X.509 Certificate
*
* @param pair the KeyPair
*/
private X509Certificate generateCertificate(KeyPair pair) throws GeneralSecurityException, IOException {
PublicKey pubKey = loadPublicKeyFromBytes(pair.getPublic().getEncoded());
PrivateKey privkey = pair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = getNotBefore();
Date to = new Date(from.getTime() + valuesHolder.getCertificateValidityInDays() * 86400000L);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(String.format(CERTIFICATE_COMMON_NAME_FORMAT, valuesHolder.getCertificateCommonName()));
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, owner);
info.set(X509CertInfo.ISSUER, owner);
info.set(X509CertInfo.KEY, new CertificateX509Key(pubKey));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId keyAlgo = AlgorithmId.get(KeyCertificateAlgorithmValuesHolder.DEFAULT_KEY_ALGORITHM);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(keyAlgo));
AlgorithmId signingAlgo = AlgorithmId.get(valuesHolder.getSigningAlgorithm());
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, signingAlgo);
// add extensions
CertificateExtensions ext = new CertificateExtensions();
ext.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(new KeyIdentifier(pubKey).getIdentifier()));
// CA public key is the same as our public key (self signed)
ext.set(AuthorityKeyIdentifierExtension.NAME, new AuthorityKeyIdentifierExtension(new KeyIdentifier(pubKey), null, null));
ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(subjectAltNames()));
info.set(X509CertInfo.EXTENSIONS, ext);
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, valuesHolder.getSigningAlgorithm());
return cert;
}
use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project Bytecoder by mirkosertic.
the class ForwardState method updateState.
/**
* Update the state with the next certificate added to the path.
*
* @param cert the certificate which is used to update the state
*/
@Override
public void updateState(X509Certificate cert) throws CertificateException, IOException, CertPathValidatorException {
if (cert == null)
return;
X509CertImpl icert = X509CertImpl.toImpl(cert);
/* see if certificate key has null parameters */
if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
keyParamsNeededFlag = true;
}
/* update certificate */
this.cert = icert;
/* update issuer DN */
issuerDN = cert.getIssuerX500Principal();
if (!X509CertImpl.isSelfIssued(cert)) {
/*
* update traversedCACerts only if this is a non-self-issued
* intermediate CA cert
*/
if (!init && cert.getBasicConstraints() != -1) {
traversedCACerts++;
}
}
/* update subjectNamesTraversed only if this is the EE cert or if
this cert is not self-issued */
if (init || !X509CertImpl.isSelfIssued(cert)) {
X500Principal subjName = cert.getSubjectX500Principal();
subjectNamesTraversed.add(X500Name.asX500Name(subjName));
try {
SubjectAlternativeNameExtension subjAltNameExt = icert.getSubjectAlternativeNameExtension();
if (subjAltNameExt != null) {
GeneralNames gNames = subjAltNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
for (GeneralName gName : gNames.names()) {
subjectNamesTraversed.add(gName.getName());
}
}
} catch (IOException e) {
if (debug != null) {
debug.println("ForwardState.updateState() unexpected " + "exception");
e.printStackTrace();
}
throw new CertPathValidatorException(e);
}
}
init = false;
}
use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension 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 org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project candlepin by candlepin.
the class JSSPKIUtility method buildStandardExtensions.
/**
* Add boilerplate extensions required by RFC 5280.
* @param certExtensions a CertificateExtensions object to modify
* @param keyPair the KeyPair used to create the SubjectKeyIdentifier extension
* @param providedExtensions A Set of provided extensions that will be added to the certificate. In some
* cases (hosted mode) access to the information in those extensions is required for creating the
* subjectKeyIdentifier.
*
* @return a modified version of the certExtensions parameter
* @throws IOException in case of encoding failures
*/
private CertificateExtensions buildStandardExtensions(CertificateExtensions certExtensions, String dn, KeyPair keyPair, Set<X509ExtensionWrapper> providedExtensions, X509Certificate caCert, String alternateName) throws IOException {
/* The RFC states that KeyUsage SHOULD be marked as critical. In previous Candlepin code we were
* not marking it critical but this constructor will. I do not believe there should be any
* compatibility issues, but I am noting it just in case. */
KeyUsageExtension keyUsage = new KeyUsageExtension();
keyUsage.set(KeyUsageExtension.DIGITAL_SIGNATURE, true);
keyUsage.set(KeyUsageExtension.KEY_ENCIPHERMENT, true);
keyUsage.set(KeyUsageExtension.DATA_ENCIPHERMENT, true);
certExtensions.add(keyUsage);
// Not critical by default
ExtendedKeyUsageExtension extendedKeyUsage = new ExtendedKeyUsageExtension();
/* JSS doesn't have a constant defined for the "clientAuth" OID so we have to put it in by hand.
* See https://tools.ietf.org/html/rfc5280#appendix-A specifically id-kp-clientAuth. This OID
* denotes that a certificate is meant for client authentication over TLS */
extendedKeyUsage.addOID(new ObjectIdentifier("1.3.6.1.5.5.7.3.2"));
certExtensions.add(extendedKeyUsage);
// Not critical for non-CA certs. -1 pathLen means it won't be encoded.
BasicConstraintsExtension basicConstraints = new BasicConstraintsExtension(false, -1);
certExtensions.add(basicConstraints);
try {
/* Not critical by default. I am extremely dubious that we actually need this extension
* but I'm keeping it because our old cert creation code added it. */
NSCertTypeExtension netscapeCertType = new NSCertTypeExtension();
netscapeCertType.set(NSCertTypeExtension.SSL_CLIENT, true);
netscapeCertType.set(NSCertTypeExtension.EMAIL, true);
certExtensions.add(netscapeCertType);
} catch (CertificateException e) {
throw new IOException("Could not construct certificate extensions", e);
}
try {
/* The JSS SubjectKeyIdentifierExtension class expects you to give it the unencoded KeyIdentifier.
* The SubjectKeyIdentifierExtension class, however, returns the encoded KeyIdentifier (an DER
* octet string). Therefore, we need to unpack the KeyIdentifier. */
byte[] encodedSki = subjectKeyWriter.getSubjectKeyIdentifier(keyPair, providedExtensions);
OCTET_STRING extOctets = (OCTET_STRING) ASN1Util.decode(new OCTET_STRING.Template(), encodedSki);
// Required to be non-critical
SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension(extOctets.toByteArray());
certExtensions.add(ski);
// Not critical by default
AuthorityKeyIdentifierExtension aki = buildAuthorityKeyIdentifier(caCert);
certExtensions.add(aki);
// Not critical by default and should *not* be critical since the subject field isn't empty
if (alternateName != null) {
SubjectAlternativeNameExtension altNames = new SubjectAlternativeNameExtension();
GeneralName[] akiName = new GeneralName[2];
akiName[0] = new GeneralName(new X500Name(dn));
akiName[1] = new GeneralName(new X500Name("CN=" + alternateName));
GeneralNames generalNames = new GeneralNames(akiName);
altNames.setGeneralNames(generalNames);
certExtensions.add(altNames);
}
} catch (InvalidBERException | GeneralNamesException | NoSuchAlgorithmException e) {
throw new IOException("Could not construct certificate extensions", e);
}
return certExtensions;
}
use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project OpenAttestation by OpenAttestation.
the class X509Builder method ipAlternativeName.
public X509Builder ipAlternativeName(String ip) {
try {
v3();
String alternativeName = ip;
if (ip.startsWith("ip:")) {
alternativeName = ip.substring(3);
}
// InetAddress ipAddress = new InetAddress.getByName(alternativeName.substring(3));
// IPAddressName ipAddressName = new IPAddressName(ipAddress.getAddress());
IPAddressName ipAddressName = new IPAddressName(alternativeName);
if (alternativeNames == null) {
alternativeNames = new GeneralNames();
}
alternativeNames.add(new GeneralName(ipAddressName));
SubjectAlternativeNameExtension san = new SubjectAlternativeNameExtension(alternativeNames);
if (certificateExtensions == null) {
certificateExtensions = new CertificateExtensions();
}
certificateExtensions.set(san.getExtensionId().toString(), san);
info.set(X509CertInfo.EXTENSIONS, certificateExtensions);
// ObjectIdentifier("2.5.29.17") , false, "ipaddress".getBytes()
} catch (Exception e) {
fault(e, "ipAlternativeName(%s)", ip);
}
return this;
}
Aggregations