use of org.bouncycastle.asn1.x509.Extension in project XobotOS by xamarin.
the class X509V3CertificateGenerator method copyAndAddExtension.
/**
* add a given extension field for the standard extensions tag (tag 3)
* copying the extension value from another certificate.
* @throws CertificateParsingException if the extension cannot be extracted.
*/
public void copyAndAddExtension(String oid, boolean critical, X509Certificate cert) throws CertificateParsingException {
byte[] extValue = cert.getExtensionValue(oid);
if (extValue == null) {
throw new CertificateParsingException("extension " + oid + " not present");
}
try {
ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue);
this.addExtension(oid, critical, value);
} catch (IOException e) {
throw new CertificateParsingException(e.toString());
}
}
use of org.bouncycastle.asn1.x509.Extension in project XobotOS by xamarin.
the class X509CertificateObject method getExtendedKeyUsage.
public List getExtendedKeyUsage() throws CertificateParsingException {
byte[] bytes = this.getExtensionBytes("2.5.29.37");
if (bytes != null) {
try {
ASN1InputStream dIn = new ASN1InputStream(bytes);
ASN1Sequence seq = (ASN1Sequence) dIn.readObject();
List list = new ArrayList();
for (int i = 0; i != seq.size(); i++) {
list.add(((DERObjectIdentifier) seq.getObjectAt(i)).getId());
}
return Collections.unmodifiableList(list);
} catch (Exception e) {
throw new CertificateParsingException("error processing extended key usage extension");
}
}
return null;
}
use of org.bouncycastle.asn1.x509.Extension in project XobotOS by xamarin.
the class X509Extensions method toASN1Object.
/**
* <pre>
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnId EXTENSION.&id ({ExtensionSet}),
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
* </pre>
*/
public DERObject toASN1Object() {
ASN1EncodableVector vec = new ASN1EncodableVector();
Enumeration e = ordering.elements();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
X509Extension ext = (X509Extension) extensions.get(oid);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(oid);
if (ext.isCritical()) {
// BEGIN android-changed
v.add(DERBoolean.TRUE);
// END android-changed
}
v.add(ext.getValue());
vec.add(new DERSequence(v));
}
return new DERSequence(vec);
}
use of org.bouncycastle.asn1.x509.Extension 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());
}
}
use of org.bouncycastle.asn1.x509.Extension in project nhin-d by DirectProject.
the class TrustChainValidator method resolveIssuers.
protected void resolveIssuers(X509Certificate certificate, /*in-out*/
Collection<X509Certificate> issuers, int chainLength, Collection<X509Certificate> anchors) {
X500Principal issuerPrin = certificate.getIssuerX500Principal();
if (issuerPrin.equals(certificate.getSubjectX500Principal())) {
// no intermediate between me, myself, and I
return;
}
// look in the issuer list and see if the certificate issuer already exists in the list
for (X509Certificate issuer : issuers) {
if (issuerPrin.equals(issuer.getSubjectX500Principal()))
// already found the certificate issuer... done
return;
}
if (chainLength >= maxIssuerChainLength) {
// bail out with what we have now
return;
}
// first check to see there is an AIA extension with one ore more caIssuer entries and attempt to resolve the
// intermediate via the URL
final Collection<X509Certificate> issuerCerts = getIntermediateCertsByAIA(certificate);
// of using resolvers
if (issuerCerts.isEmpty()) {
final String address = this.getIssuerAddress(certificate);
if (address == null || address.isEmpty())
// not much we can do about this... the resolver interface only knows how to work with addresses
return;
// multiple resolvers
for (CertificateResolver publicResolver : certResolvers) {
Collection<X509Certificate> holdCerts = null;
try {
holdCerts = publicResolver.getCertificates(new InternetAddress(address));
} catch (AddressException e) {
continue;
} catch (Exception e) {
/* no-op*/
}
if (holdCerts != null && holdCerts.size() > 0)
issuerCerts.addAll(holdCerts);
}
}
if (issuerCerts.size() == 0)
// no intermediates.. just return
return;
boolean issuerFoundInAnchors = false;
Collection<X509Certificate> searchForParentIssuers = new ArrayList<X509Certificate>();
for (X509Certificate issuerCert : issuerCerts) {
if (issuerCert.getSubjectX500Principal().equals(issuerPrin) && !isIssuerInCollection(issuers, issuerCert) && !isIssuerInAnchors(anchors, issuerCert)) /* if we hit an anchor then stop */
{
searchForParentIssuers.add(issuerCert);
} else if (isIssuerInAnchors(anchors, issuerCert)) {
issuerFoundInAnchors = true;
break;
}
}
// the go up the next level in the chain
if (!issuerFoundInAnchors) {
for (X509Certificate issuerCert : searchForParentIssuers) {
issuers.add(issuerCert);
// see if this issuer also has intermediate certs
resolveIssuers(issuerCert, issuers, chainLength + 1, anchors);
}
}
}
Aggregations