use of com.android.org.bouncycastle.asn1.x509.KeyPurposeId in project robovm by robovm.
the class TestKeyStore method createCertificate.
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
// Note that there is no way to programmatically make a
// Certificate using java.* or javax.* APIs. The
// CertificateFactory interface assumes you want to read
// in a stream of bytes, typically the X.509 factory would
// allow ASN.1 DER encoded bytes and optionally some PEM
// formats. Here we use Bouncy Castle's
// X509V3CertificateGenerator and related classes.
long millisPerDay = 24 * 60 * 60 * 1000;
long now = System.currentTimeMillis();
Date start = new Date(now - millisPerDay);
Date end = new Date(now + millisPerDay);
BigInteger serial = BigInteger.valueOf(1);
String keyAlgorithm = privateKey.getAlgorithm();
String signatureAlgorithm;
if (keyAlgorithm.equals("RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else if (keyAlgorithm.equals("DSA")) {
signatureAlgorithm = "sha1WithDSA";
} else if (keyAlgorithm.equals("EC")) {
signatureAlgorithm = "sha1WithECDSA";
} else if (keyAlgorithm.equals("EC_RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else {
throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
}
X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
x509cg.setSubjectDN(subject);
x509cg.setIssuerDN(issuer);
x509cg.setNotBefore(start);
x509cg.setNotAfter(end);
x509cg.setPublicKey(publicKey);
x509cg.setSignatureAlgorithm(signatureAlgorithm);
x509cg.setSerialNumber(serial);
if (keyUsage != 0) {
x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
}
if (ca) {
x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
}
for (int i = 0; i < extendedKeyUsages.size(); i++) {
KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
boolean critical = criticalExtendedKeyUsages.get(i);
x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
}
for (GeneralName subjectAltName : subjectAltNames) {
x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
}
if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
}
if (privateKey instanceof ECPrivateKey) {
/*
* bouncycastle needs its own ECPrivateKey implementation
*/
KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
privateKey = kf.generatePrivate(ks);
}
X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
if (StandardNames.IS_RI) {
/*
* The RI can't handle the BC EC signature algorithm
* string of "ECDSA", since it expects "...WITHEC...",
* so convert from BC to RI X509Certificate
* implementation via bytes.
*/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
Certificate c = cf.generateCertificate(bais);
x509c = (X509Certificate) c;
}
return x509c;
}
use of com.android.org.bouncycastle.asn1.x509.KeyPurposeId in project zaproxy by zaproxy.
the class SslCertificateUtils method createRootCA.
/**
* Creates a new Root CA certificate and returns private and public key as
* {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
*
* @return
* @throws NoSuchAlgorithmException If no providers are found
* for 'RSA' key pair generator
* or 'SHA1PRNG' Secure random number generator
* @throws IllegalStateException in case of errors during assembling {@link KeyStore}
*/
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
final Date startDate = Calendar.getInstance().getTime();
final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));
final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
final KeyPair keypair = g.genKeyPair();
final PrivateKey privKey = keypair.getPrivate();
final PublicKey pubKey = keypair.getPublic();
Security.addProvider(new BouncyCastleProvider());
Random rnd = new Random();
// using the hash code of the user's name and home path, keeps anonymity
// but also gives user a chance to distinguish between each other
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode()));
namebld.addRDN(BCStyle.O, "OWASP Root CA");
namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
namebld.addRDN(BCStyle.C, "xx");
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);
KeyStore ks = null;
try {
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey);
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert });
} catch (final Exception e) {
throw new IllegalStateException("Errors during assembling root CA.", e);
}
return ks;
}
use of com.android.org.bouncycastle.asn1.x509.KeyPurposeId 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