use of org.openecard.bouncycastle.asn1.x500.RDN in project xipki by xipki.
the class XmlX509Certprofile method initialize0.
// method initialize
private void initialize0(X509ProfileType conf) throws CertprofileException {
if (conf.getVersion() != null) {
String versionText = conf.getVersion();
this.version = X509CertVersion.forName(versionText);
if (this.version == null) {
throw new CertprofileException(String.format("invalid version '%s'", versionText));
}
} else {
this.version = X509CertVersion.v3;
}
if (conf.getSignatureAlgorithms() != null) {
List<String> algoNames = conf.getSignatureAlgorithms().getAlgorithm();
List<String> list = new ArrayList<>(algoNames.size());
for (String algoName : algoNames) {
try {
list.add(AlgorithmUtil.canonicalizeSignatureAlgo(algoName));
} catch (NoSuchAlgorithmException ex) {
throw new CertprofileException(ex.getMessage(), ex);
}
}
this.signatureAlgorithms = Collections.unmodifiableList(list);
}
this.raOnly = conf.isRaOnly();
this.maxSize = conf.getMaxSize();
this.validity = CertValidity.getInstance(conf.getValidity());
String str = conf.getCertLevel();
if ("RootCA".equalsIgnoreCase(str)) {
this.certLevel = X509CertLevel.RootCA;
} else if ("SubCA".equalsIgnoreCase(str)) {
this.certLevel = X509CertLevel.SubCA;
} else if ("EndEntity".equalsIgnoreCase(str)) {
this.certLevel = X509CertLevel.EndEntity;
} else {
throw new CertprofileException("invalid CertLevel '" + str + "'");
}
str = conf.getNotBeforeTime();
if ("midnight".equalsIgnoreCase(str)) {
this.notBeforeMidnight = true;
} else if ("current".equalsIgnoreCase(str)) {
this.notBeforeMidnight = false;
} else {
throw new CertprofileException("invalid notBefore '" + str + "'");
}
String specBehavior = conf.getSpecialBehavior();
if (specBehavior != null) {
this.specialBehavior = SpecialX509CertprofileBehavior.forName(specBehavior);
}
this.duplicateKeyPermitted = conf.isDuplicateKey();
this.serialNumberInReqPermitted = conf.isSerialNumberInReq();
// KeyAlgorithms
KeyAlgorithms keyAlgos = conf.getKeyAlgorithms();
if (keyAlgos != null) {
this.keyAlgorithms = XmlX509CertprofileUtil.buildKeyAlgorithms(keyAlgos);
}
// parameters
Parameters confParams = conf.getParameters();
if (confParams == null) {
parameters = null;
} else {
Map<String, String> tmpMap = new HashMap<>();
for (NameValueType nv : confParams.getParameter()) {
tmpMap.put(nv.getName(), nv.getValue());
}
parameters = Collections.unmodifiableMap(tmpMap);
}
// Subject
Subject subject = conf.getSubject();
duplicateSubjectPermitted = subject.isDuplicateSubjectPermitted();
List<RdnControl> subjectDnControls = new LinkedList<>();
for (RdnType rdn : subject.getRdn()) {
ASN1ObjectIdentifier type = new ASN1ObjectIdentifier(rdn.getType().getValue());
List<Pattern> patterns = null;
if (CollectionUtil.isNonEmpty(rdn.getRegex())) {
patterns = new LinkedList<>();
for (String regex : rdn.getRegex()) {
Pattern pattern = Pattern.compile(regex);
patterns.add(pattern);
}
}
if (patterns == null) {
Pattern pattern = SubjectDnSpec.getPattern(type);
if (pattern != null) {
patterns = Arrays.asList(pattern);
}
}
Range range = (rdn.getMinLen() != null || rdn.getMaxLen() != null) ? new Range(rdn.getMinLen(), rdn.getMaxLen()) : null;
RdnControl rdnControl = new RdnControl(type, rdn.getMinOccurs(), rdn.getMaxOccurs());
subjectDnControls.add(rdnControl);
StringType stringType = XmlX509CertprofileUtil.convertStringType(rdn.getStringType());
rdnControl.setStringType(stringType);
rdnControl.setStringLengthRange(range);
rdnControl.setPatterns(patterns);
rdnControl.setPrefix(rdn.getPrefix());
rdnControl.setSuffix(rdn.getSuffix());
rdnControl.setGroup(rdn.getGroup());
SubjectDnSpec.fixRdnControl(rdnControl);
}
this.subjectControl = new SubjectControl(subjectDnControls, subject.isKeepRdnOrder());
this.incSerialNoIfSubjectExists = subject.isIncSerialNumber();
// Extensions
ExtensionsType extensionsType = conf.getExtensions();
// Extension controls
this.extensionControls = XmlX509CertprofileUtil.buildExtensionControls(extensionsType);
Set<ASN1ObjectIdentifier> extnIds = new HashSet<>(this.extensionControls.keySet());
// SubjectToSubjectAltName
initSubjectToSubjectAltNames(extensionsType);
// AdditionalInformation
initAdditionalInformation(extnIds, extensionsType);
// Admission
initAdmission(extnIds, extensionsType);
// AuthorityInfoAccess
initAuthorityInfoAccess(extnIds, extensionsType);
// AuthorityKeyIdentifier
initAuthorityKeyIdentifier(extnIds, extensionsType);
// AuthorizationTemplate
initAuthorizationTemplate(extnIds, extensionsType);
// BasicConstrains
initBasicConstraints(extnIds, extensionsType);
// BiometricInfo
initBiometricInfo(extnIds, extensionsType);
// Certificate Policies
initCertificatePolicies(extnIds, extensionsType);
// ExtendedKeyUsage
initExtendedKeyUsage(extnIds, extensionsType);
// Inhibit anyPolicy
initInhibitAnyPolicy(extnIds, extensionsType);
// KeyUsage
initKeyUsage(extnIds, extensionsType);
// Name Constrains
initNameConstraints(extnIds, extensionsType);
// Policy Constraints
initPolicyConstraints(extnIds, extensionsType);
// Policy Mappings
initPolicyMappings(extnIds, extensionsType);
// PrivateKeyUsagePeriod
initPrivateKeyUsagePeriod(extnIds, extensionsType);
// QCStatements
initQcStatements(extnIds, extensionsType);
// Restriction
initRestriction(extnIds, extensionsType);
// SMIMECapatibilities
initSmimeCapabilities(extnIds, extensionsType);
// SubjectAltNameMode
initSubjectAlternativeName(extnIds, extensionsType);
// SubjectInfoAccess
initSubjectInfoAccess(extnIds, extensionsType);
// TlsFeature
initTlsFeature(extnIds, extensionsType);
// validityModel
initValidityModel(extnIds, extensionsType);
// SubjectDirectoryAttributes
initSubjectDirAttrs(extnIds, extensionsType);
// constant extensions
this.constantExtensions = XmlX509CertprofileUtil.buildConstantExtesions(extensionsType);
if (this.constantExtensions != null) {
extnIds.removeAll(this.constantExtensions.keySet());
}
// validate the configuration
if (subjectToSubjectAltNameModes != null) {
ASN1ObjectIdentifier type = Extension.subjectAlternativeName;
if (!extensionControls.containsKey(type)) {
throw new CertprofileException("subjectToSubjectAltNames cannot be configured if extension" + " subjectAltNames is not permitted");
}
if (subjectAltNameModes != null) {
for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) {
GeneralNameTag nameTag = subjectToSubjectAltNameModes.get(attrType);
boolean allowed = false;
for (GeneralNameMode m : subjectAltNameModes) {
if (m.getTag() == nameTag) {
allowed = true;
break;
}
}
if (!allowed) {
throw new CertprofileException("target SubjectAltName type " + nameTag + " is not allowed");
}
}
}
}
// Remove the extension processed not be the CertProfile, but by the CA
extnIds.remove(Extension.issuerAlternativeName);
extnIds.remove(Extension.authorityInfoAccess);
extnIds.remove(Extension.cRLDistributionPoints);
extnIds.remove(Extension.freshestCRL);
extnIds.remove(Extension.subjectKeyIdentifier);
extnIds.remove(Extension.subjectInfoAccess);
extnIds.remove(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
Set<ASN1ObjectIdentifier> copyOfExtnIds = new HashSet<>(extnIds);
for (ASN1ObjectIdentifier extnId : copyOfExtnIds) {
Object extnValue = getExtensionValue(extnId, extensionsType, Object.class);
boolean processed = initExtraExtension(extnId, extensionControls.get(extnId), extnValue);
if (processed) {
extnIds.remove(extnId);
}
}
if (!extnIds.isEmpty()) {
throw new CertprofileException("Cannot process the extensions: " + extnIds);
}
}
use of org.openecard.bouncycastle.asn1.x500.RDN in project xipki by xipki.
the class XmlX509Certprofile method createRequestedSubjectAltNames.
private GeneralNames createRequestedSubjectAltNames(X500Name requestedSubject, X500Name grantedSubject, Extensions requestedExtensions) throws BadCertTemplateException {
ASN1Encodable extValue = (requestedExtensions == null) ? null : requestedExtensions.getExtensionParsedValue(Extension.subjectAlternativeName);
if (extValue == null && subjectToSubjectAltNameModes == null) {
return null;
}
GeneralNames reqNames = (extValue == null) ? null : GeneralNames.getInstance(extValue);
if (subjectAltNameModes == null && subjectToSubjectAltNameModes == null) {
return reqNames;
}
List<GeneralName> grantedNames = new LinkedList<>();
// copy the required attributes of Subject
if (subjectToSubjectAltNameModes != null) {
for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) {
GeneralNameTag tag = subjectToSubjectAltNameModes.get(attrType);
RDN[] rdns = grantedSubject.getRDNs(attrType);
if (rdns == null) {
rdns = requestedSubject.getRDNs(attrType);
}
if (rdns == null) {
continue;
}
for (RDN rdn : rdns) {
String rdnValue = X509Util.rdnValueToString(rdn.getFirst().getValue());
switch(tag) {
case rfc822Name:
case dNSName:
case uniformResourceIdentifier:
case iPAddress:
case directoryName:
case registeredID:
grantedNames.add(new GeneralName(tag.getTag(), rdnValue));
break;
default:
throw new RuntimeException("should not reach here, unknown GeneralName tag " + tag);
}
// end switch (tag)
}
}
}
// copy the requested SubjectAltName entries
if (reqNames != null) {
GeneralName[] reqL = reqNames.getNames();
for (int i = 0; i < reqL.length; i++) {
grantedNames.add(X509CertprofileUtil.createGeneralName(reqL[i], subjectAltNameModes));
}
}
return grantedNames.isEmpty() ? null : new GeneralNames(grantedNames.toArray(new GeneralName[0]));
}
use of org.openecard.bouncycastle.asn1.x500.RDN in project open-ecard by ecsec.
the class ListCertificates method getUniqueIdentifier.
private String getUniqueIdentifier(X509Certificate cert) {
// try to get SERIALNUMBER from subject
X500Name sub = X500Name.getInstance(cert.getSubjectX500Principal().getEncoded());
RDN[] serials = sub.getRDNs(BCStyle.SERIALNUMBER);
if (serials.length >= 1) {
AttributeTypeAndValue serialValueType = serials[0].getFirst();
ASN1Encodable serialValue = serialValueType.getValue();
if (ASN1String.class.isInstance(serialValue)) {
return ASN1String.class.cast(serialValue).getString();
}
}
// no SERIALNUMBER, hash subject and cross fingers that this is unique across replacement cards
try {
SHA256Digest digest = new SHA256Digest();
byte[] subData = sub.getEncoded();
digest.update(subData, 0, subData.length);
byte[] hashResult = new byte[digest.getDigestSize()];
digest.doFinal(hashResult, 0);
String hashedSub = ByteUtils.toWebSafeBase64String(hashResult);
return hashedSub;
} catch (IOException ex) {
throw new RuntimeException("Failed to encode subject.", ex);
}
}
use of org.openecard.bouncycastle.asn1.x500.RDN in project credhub by cloudfoundry-incubator.
the class UserContext method parseAppIdentifier.
private String parseAppIdentifier(String subjectDn) {
final X500Name dnName = new X500Name(subjectDn);
final RDN[] rdNs = dnName.getRDNs(BCStyle.OU);
return rdNs[0].getFirst().getValue().toString();
}
use of org.openecard.bouncycastle.asn1.x500.RDN in project jruby-openssl by jruby.
the class X509Extension method formatGeneralName.
@SuppressWarnings("unchecked")
private static boolean formatGeneralName(final GeneralName name, final ByteList out, final boolean slashed) {
final ASN1Encodable obj = name.getName();
String val;
boolean tagged = false;
switch(name.getTagNo()) {
case GeneralName.rfc822Name:
if (!tagged)
out.append('e').append('m').append('a').append('i').append('l').append(':');
tagged = true;
case GeneralName.dNSName:
if (!tagged)
out.append('D').append('N').append('S').append(':');
tagged = true;
case GeneralName.uniformResourceIdentifier:
if (!tagged)
out.append('U').append('R').append('I').append(':');
val = DERIA5String.getInstance(obj).getString();
out.append(ByteList.plain(val));
break;
case GeneralName.directoryName:
out.append('D').append('i').append('r').append('N').append('a').append('m').append('e').append(':');
final X500Name dirName = X500Name.getInstance(obj);
if (slashed) {
final RDN[] rdns = dirName.getRDNs();
final Hashtable defaultSymbols = getDefaultSymbols();
for (int i = 0; i < rdns.length; i++) {
appendRDN(out.append('/'), rdns[i], defaultSymbols);
}
} else {
out.append(ByteList.plain(dirName.toString()));
}
break;
case GeneralName.iPAddress:
out.append('I').append('P').append(':');
final byte[] ip = ((ASN1OctetString) name.getName()).getOctets();
int len = ip.length;
boolean ip4 = len == 4;
if (ip4) {
for (int i = 0; i < ip.length; i++) {
out.append(ConvertBytes.intToCharBytes(((int) ip[i]) & 0xff));
if (i != len - 1)
out.append('.');
}
} else {
for (int i = 0; i < ip.length; i += 2) {
out.append(ConvertBytes.intToHexBytes(((ip[i] & 0xff) << 8 | (ip[i + 1] & 0xff))));
if (i != len - 2)
out.append(':');
}
}
break;
case GeneralName.otherName:
out.append('o').append('t').append('h').append('e').append('r').append('N').append('a').append('m').append('e').append(':');
out.append(ByteList.plain(obj.toString()));
return true;
// tagged = true;
case GeneralName.registeredID:
out.append('R').append('I').append('D').append(':');
// tagged = true;
default:
out.append(ByteList.plain(obj.toString()));
}
return false;
}
Aggregations