use of org.openecard.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.
the class PKIXCertPathValidatorSpi method engineValidate.
// END android-added
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
if (!(params instanceof PKIXParameters)) {
throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
}
ExtendedPKIXParameters paramsPKIX;
if (params instanceof ExtendedPKIXParameters) {
paramsPKIX = (ExtendedPKIXParameters) params;
} else {
paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters) params);
}
if (paramsPKIX.getTrustAnchors() == null) {
throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
}
//
// 6.1.1 - inputs
//
//
// (a)
//
List certs = certPath.getCertificates();
int n = certs.size();
if (certs.isEmpty()) {
throw new CertPathValidatorException("Certification path is empty.", null, certPath, 0);
}
// BEGIN android-added
{
X509Certificate cert = (X509Certificate) certs.get(0);
if (cert != null) {
BigInteger serial = cert.getSerialNumber();
if (serial != null && SERIAL_BLACKLIST.contains(serial)) {
// emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
String message = "Certificate revocation of serial 0x" + serial.toString(16);
System.out.println(message);
AnnotatedException e = new AnnotatedException(message);
throw new CertPathValidatorException(e.getMessage(), e, certPath, 0);
}
}
}
// END android-added
//
// (b)
//
// Date validDate = CertPathValidatorUtilities.getValidDate(paramsPKIX);
//
// (c)
//
Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
//
// (d)
//
TrustAnchor trust;
try {
trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
} catch (AnnotatedException e) {
throw new CertPathValidatorException(e.getMessage(), e, certPath, certs.size() - 1);
}
if (trust == null) {
throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
}
//
// (e), (f), (g) are part of the paramsPKIX object.
//
Iterator certIter;
int index = 0;
int i;
// Certificate for each interation of the validation loop
// Signature information for each iteration of the validation loop
//
// 6.1.2 - setup
//
//
// (a)
//
List[] policyNodes = new ArrayList[n + 1];
for (int j = 0; j < policyNodes.length; j++) {
policyNodes[j] = new ArrayList();
}
Set policySet = new HashSet();
policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
policyNodes[0].add(validPolicyTree);
//
// (b) and (c)
//
PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
// (d)
//
int explicitPolicy;
Set acceptablePolicies = new HashSet();
if (paramsPKIX.isExplicitPolicyRequired()) {
explicitPolicy = 0;
} else {
explicitPolicy = n + 1;
}
//
// (e)
//
int inhibitAnyPolicy;
if (paramsPKIX.isAnyPolicyInhibited()) {
inhibitAnyPolicy = 0;
} else {
inhibitAnyPolicy = n + 1;
}
//
// (f)
//
int policyMapping;
if (paramsPKIX.isPolicyMappingInhibited()) {
policyMapping = 0;
} else {
policyMapping = n + 1;
}
//
// (g), (h), (i), (j)
//
PublicKey workingPublicKey;
X500Principal workingIssuerName;
X509Certificate sign = trust.getTrustedCert();
try {
if (sign != null) {
workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
workingPublicKey = sign.getPublicKey();
} else {
workingIssuerName = new X500Principal(trust.getCAName());
workingPublicKey = trust.getCAPublicKey();
}
} catch (IllegalArgumentException ex) {
throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
}
AlgorithmIdentifier workingAlgId = null;
try {
workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
} catch (CertPathValidatorException e) {
throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
}
DERObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId();
DEREncodable workingPublicKeyParameters = workingAlgId.getParameters();
//
// (k)
//
int maxPathLength = n;
if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
}
//
// initialize CertPathChecker's
//
List pathCheckers = paramsPKIX.getCertPathCheckers();
certIter = pathCheckers.iterator();
while (certIter.hasNext()) {
((PKIXCertPathChecker) certIter.next()).init(false);
}
X509Certificate cert = null;
for (index = certs.size() - 1; index >= 0; index--) {
// BEGIN android-added
if (isPublicKeyBlackListed(workingPublicKey)) {
// emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
String message = "Certificate revocation of public key " + workingPublicKey;
System.out.println(message);
AnnotatedException e = new AnnotatedException(message);
throw new CertPathValidatorException(e.getMessage(), e, certPath, index);
}
// END android-added
// try
// {
//
// i as defined in the algorithm description
//
i = n - index;
//
// set certificate to be checked in this round
// sign and workingPublicKey and workingIssuerName are set
// at the end of the for loop and initialized the
// first time from the TrustAnchor
//
cert = (X509Certificate) certs.get(index);
boolean verificationAlreadyPerformed = (index == certs.size() - 1);
//
// 6.1.3
//
RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator);
validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
if (i != n) {
if (cert != null && cert.getVersion() == 1) {
throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
}
RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
// (h)
explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
//
// (i)
//
explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
// (j)
inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
// (k)
RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
// (l)
maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
// (m)
maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
// (n)
RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
Set criticalExtensions = cert.getCriticalExtensionOIDs();
if (criticalExtensions != null) {
criticalExtensions = new HashSet(criticalExtensions);
// these extensions are handled by the algorithm
criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
} else {
criticalExtensions = new HashSet();
}
// (o)
RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
// set signing certificate for next round
sign = cert;
// (c)
workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
// (d)
try {
workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index);
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
}
workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
// (f)
workingPublicKeyAlgorithm = workingAlgId.getObjectId();
// (e)
workingPublicKeyParameters = workingAlgId.getParameters();
}
}
//
// 6.1.5 Wrap-up procedure
//
explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
//
// (c) (d) and (e) are already done
//
//
// (f)
//
Set criticalExtensions = cert.getCriticalExtensionOIDs();
if (criticalExtensions != null) {
criticalExtensions = new HashSet(criticalExtensions);
// these extensions are handled by the algorithm
criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
} else {
criticalExtensions = new HashSet();
}
RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
if ((explicitPolicy > 0) || (intersection != null)) {
return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
}
throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.
the class X509CRLEntryObject method getExtensionOIDs.
private Set getExtensionOIDs(boolean critical) {
X509Extensions extensions = c.getExtensions();
if (extensions != null) {
Set set = new HashSet();
Enumeration e = extensions.oids();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
X509Extension ext = extensions.getExtension(oid);
if (critical == ext.isCritical()) {
set.add(oid.getId());
}
}
return set;
}
return null;
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.
the class X509CRLObject method toString.
/**
* Returns a string representation of this CRL.
*
* @return a string representation of this CRL.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
String nl = System.getProperty("line.separator");
buf.append(" Version: ").append(this.getVersion()).append(nl);
buf.append(" IssuerDN: ").append(this.getIssuerDN()).append(nl);
buf.append(" This update: ").append(this.getThisUpdate()).append(nl);
buf.append(" Next update: ").append(this.getNextUpdate()).append(nl);
buf.append(" Signature Algorithm: ").append(this.getSigAlgName()).append(nl);
byte[] sig = this.getSignature();
buf.append(" Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
for (int i = 20; i < sig.length; i += 20) {
if (i < sig.length - 20) {
buf.append(" ").append(new String(Hex.encode(sig, i, 20))).append(nl);
} else {
buf.append(" ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl);
}
}
X509Extensions extensions = c.getTBSCertList().getExtensions();
if (extensions != null) {
Enumeration e = extensions.oids();
if (e.hasMoreElements()) {
buf.append(" Extensions: ").append(nl);
}
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
X509Extension ext = extensions.getExtension(oid);
if (ext.getValue() != null) {
byte[] octs = ext.getValue().getOctets();
ASN1InputStream dIn = new ASN1InputStream(octs);
buf.append(" critical(").append(ext.isCritical()).append(") ");
try {
if (oid.equals(X509Extensions.CRLNumber)) {
buf.append(new CRLNumber(DERInteger.getInstance(dIn.readObject()).getPositiveValue())).append(nl);
} else if (oid.equals(X509Extensions.DeltaCRLIndicator)) {
buf.append("Base CRL: " + new CRLNumber(DERInteger.getInstance(dIn.readObject()).getPositiveValue())).append(nl);
} else if (oid.equals(X509Extensions.IssuingDistributionPoint)) {
buf.append(new IssuingDistributionPoint((ASN1Sequence) dIn.readObject())).append(nl);
} else if (oid.equals(X509Extensions.CRLDistributionPoints)) {
buf.append(new CRLDistPoint((ASN1Sequence) dIn.readObject())).append(nl);
} else if (oid.equals(X509Extensions.FreshestCRL)) {
buf.append(new CRLDistPoint((ASN1Sequence) dIn.readObject())).append(nl);
} else {
buf.append(oid.getId());
buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
}
} catch (Exception ex) {
buf.append(oid.getId());
buf.append(" value = ").append("*****").append(nl);
}
} else {
buf.append(nl);
}
}
}
Set set = getRevokedCertificates();
if (set != null) {
Iterator it = set.iterator();
while (it.hasNext()) {
buf.append(it.next());
buf.append(nl);
}
}
return buf.toString();
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.
the class X509V2AttributeCertificate method getExtensionOIDs.
private Set getExtensionOIDs(boolean critical) {
X509Extensions extensions = cert.getAcinfo().getExtensions();
if (extensions != null) {
Set set = new HashSet();
Enumeration e = extensions.oids();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
X509Extension ext = extensions.getExtension(oid);
if (ext.isCritical() == critical) {
set.add(oid.getId());
}
}
return set;
}
return null;
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project nhin-d by DirectProject.
the class PKCS11Commands method createCSR.
@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
final String alias = StringArrayUtil.getRequiredValue(args, 0);
final String commonName = StringArrayUtil.getRequiredValue(args, 1);
final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
// make sure we have a valid keyUsage
if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
System.out.println("Invalid key usage.");
return;
}
final Vector<String> additionalRDNFields = new Vector<String>();
int cnt = 4;
String rdnField;
do {
rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
if (!StringUtils.isEmpty(rdnField))
additionalRDNFields.add(rdnField);
} while (!StringUtils.isEmpty(rdnField));
try {
final KeyStore ks = mgr.getKS();
if (!ks.containsAlias(alias)) {
System.out.println("Entry with key name " + alias + " does not exist.");
return;
}
final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
if (storedCert == null) {
System.out.println("Key name " + alias + " does not contain a certificate that can be exported. This key may not be an RSA key pair.");
return;
}
final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
if (privKey == null) {
System.out.println("Failed to object private key. This key may not be an RSA key pair.");
return;
}
// create the CSR
// create the extensions that we want
final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
// Key Usage
int usage;
if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
usage = KeyUsage.keyEncipherment;
else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
usage = KeyUsage.digitalSignature;
else
usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
// Subject Alt Name
int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
// Extended Key Usage
final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
purposes.add(KeyPurposeId.id_kp_emailProtection);
extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
// Basic constraint
final BasicConstraints bc = new BasicConstraints(false);
extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
// create the extension requests
final X509Extensions exts = extsGen.generate();
final ASN1EncodableVector attributes = new ASN1EncodableVector();
final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
attributes.add(attribute);
final DERSet requestedAttributes = new DERSet(attributes);
// create the DN
final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
final X509Principal xName = new X509Principal(true, subjectPrin.getName());
// create the CSR
final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
final byte[] encodedCSR = request.getEncoded();
final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
final File csrFile = new File(alias + "-CSR.pem");
FileUtils.writeStringToFile(csrFile, csrString);
System.out.println("CSR written to " + csrFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to create CSR : " + e.getMessage());
}
}
Aggregations