List of usage examples for org.bouncycastle.asn1.x509 X509Extensions BasicConstraints
ASN1ObjectIdentifier BasicConstraints
To view the source code for org.bouncycastle.asn1.x509 X509Extensions BasicConstraints.
Click Source Link
From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java
License:Open Source License
@Override public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer, PrivateKey signingKey, Date notAfter) { signer = (signingKey == null ? signer : subjectDn); signingKey = (signingKey == null ? keys.getPrivate() : signingKey); EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(), subjectDn.toString()).info(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4) .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000)))); certGen.setIssuerDN(signer);/* w ww. j a v a 2s. c o m*/ certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); try { certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keys.getPublic())); } catch (InvalidKeyException e) { LOG.error("Error adding subject key identifier extension.", e); } Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); certGen.setNotAfter(notAfter); certGen.setSubjectDN(subjectDn); certGen.setPublicKey(keys.getPublic()); certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM); try { X509Certificate cert = certGen.generate(signingKey, PROVIDER); cert.checkValidity(); return cert; } catch (Exception e) { LOG.fatal(e, e); return null; } }
From source file:com.example.androidtest.SslUtil.java
License:Open Source License
/** * Generates a new, self-signed X509 V3 certificate for a KeyPair. * /*from ww w .j a v a 2 s . c o m*/ * @param pair the {@link KeyPair} to be used * @param name X.500 distinguished name * @param notBefore not valid before this date * @param notAfter not valid after this date * @param serialNumber serial number * @return the new certificate * @throws GeneralSecurityException on error generating the certificate */ @SuppressWarnings("deprecation") public static X509Certificate generateX509V3Certificate(KeyPair pair, String name, Date notBefore, Date notAfter, BigInteger serialNumber) throws GeneralSecurityException { java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name dnName = new X509Name(name); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setNotBefore(notBefore); certGen.setNotAfter(notAfter); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // For self-signed certificates, OpenSSL 0.9.6 has specific requirements // about certificate and extension content. Quoting the `man verify`: // // In OpenSSL 0.9.6 and later all certificates whose subject name matches // the issuer name of the current certificate are subject to further // tests. The relevant authority key identifier components of the current // certificate (if present) must match the subject key identifier (if // present) and issuer and serial number of the candidate issuer, in // addition the keyUsage extension of the candidate issuer (if present) // must permit certificate signing. // // In the code that follows, // - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign); // - the Authority Key Identifier extension is added, matching the // subject key identifier, and using the issuer, and serial number. certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier(pair.getPublic(), dnName, serialNumber); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, true, authIdentifier); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new SubjectKeyIdentifierStructure(pair.getPublic())); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "googletv@test.test"))); // This method is deprecated, but Android Eclair does not provide the // generate() methods. X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), "BC"); return cert; }
From source file:com.integralblue.httpresponsecache.compat.java.security.TestKeyStore.java
License:Apache License
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<GeneralName> subjectAltNames, Vector<GeneralSubtree> permittedNameConstraints, Vector<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;/* w w w .ja v a2s . c om*/ 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 (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, excludedNameConstraints)); } 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; }
From source file:com.intirix.cloudpasswordmanager.services.ssl.CertPinningServiceImplUnitSpec.java
License:Apache License
public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); return certGen.generateX509Certificate(pair.getPrivate(), "BC"); }
From source file:com.otterca.common.crypto.X509CertificateBuilderImpl.java
License:Apache License
/** * Set Basic Constraint (RFC3280 4.2.1.10). Field validation is handled by * validator - we do not attempt to clean up values here. *//*from w w w .ja v a2s .co m*/ protected final void setBasicConstraint() { if (basicConstraint) { if (pathLengthConstraint == null) { generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(basicConstraint)); } else { generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(pathLengthConstraint)); } } }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
static private X509V3CertificateGenerator addCaExtensions(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyCertSign | KeyUsage.cRLSign)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // netscape-cert-type "2.16.840.1.113730.1.1" // * bit-0 SSL client - 128 // * bit-1 SSL server - 64 // * bit-2 S/MIME - 32 // * bit-3 Object Signing - 16 // * bit-4 Reserved - 8 // * bit-5 SSL CA - 4 // * bit-6 S/MIME CA - 2 // * bit-7 Object Signing CA - 1 gen.addExtension(netscapeCertType, false, new DERBitString(new byte[] { Byte.MAX_VALUE })); // was 4 addSubjectKeyIdentifier(gen, pubKey); addAuthorityKeyIdentifier(gen, pubKey); return gen;/*from w w w . j av a 2 s .c o m*/ }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
@SuppressWarnings("unused") static private X509V3CertificateGenerator addServerExtensions(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // netscape-cert-type "2.16.840.1.113730.1.1" // * bit-0 SSL client - 128 // * bit-1 SSL server - 64 // * bit-2 S/MIME - 32 // * bit-3 Object Signing - 16 // * bit-4 Reserved - 8 // * bit-5 SSL CA - 4 // * bit-6 S/MIME CA - 2 // * bit-7 Object Signing CA - 1 gen.addExtension(netscapeCertType, false, new DERBitString(new byte[] { -16 })); // was 4 addSubjectKeyIdentifier(gen, pubKey); addAuthorityKeyIdentifier(gen, pubKey); return gen;/* w w w . j a v a 2s .c o m*/ }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
static private X509V3CertificateGenerator addSSLServerExtensions(X509V3CertificateGenerator gen) { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); gen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature)); Vector<DERObjectIdentifier> extendedKeyUsageV = new Vector<DERObjectIdentifier>(); extendedKeyUsageV.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsageV.add(KeyPurposeId.id_kp_clientAuth); // Netscape Server Gated Crypto // extendedKeyUsageV.add(new DERObjectIdentifier("2.16.840.1.113730.4.1")); // Microsoft Server Gated Crypto // extendedKeyUsageV // .add(new DERObjectIdentifier("1.3.6.1.4.1.311.10.3.3")); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(extendedKeyUsageV)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // gen.addExtension(netscapeCertType, false, new DERBitString( // new byte[] { 64 })); return gen;//from ww w . j a v a 2 s . c o m }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
static private X509V3CertificateGenerator addClientExtensions(X509V3CertificateGenerator gen) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); return gen;// w w w .ja v a 2s. c o m }
From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java
License:Apache License
private X509Certificate generateV3Certificate(KeyPair pair, String certSubjectDN, Calendar before, Calendar expiry) throws CryptoException { X509V3CertificateGenerator cert = new X509V3CertificateGenerator(); /* Set the certificate serial number to a random number */ Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); /* Generates a number between 0 and 2^32 as the serial */ BigInteger serial = BigInteger.valueOf(rand.nextInt(Integer.MAX_VALUE)); logger.info("Setting X509 Cert Serial to: " + serial); cert.setSerialNumber(serial);/* ww w . j a v a2 s . co m*/ /* Set the certificate issuer */ cert.setIssuerDN(new X500Principal(this.certIssuerDN)); /* Set the start of valid period. */ cert.setNotBefore(before.getTime()); /* Set the certificate expiry date. */ cert.setNotAfter(expiry.getTime()); /* Set the subject */ cert.setSubjectDN(new X500Principal(certSubjectDN)); cert.setPublicKey(pair.getPublic()); /* Signature algorithm, this may need to be changed if not all hosts have SHA256 and RSA implementations */ cert.setSignatureAlgorithm("SHA512withRSA"); cert.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); /* Only for signing */ cert.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign)); cert.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); /* Set a contact email address for the issuer */ cert.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, this.certIssuerEmail))); logger.debug("Generating X509Certificate for key pair: " + pair); try { /* Use the BouncyCastle provider to actually generate the X509Certificate now */ return cert.generateX509Certificate(pair.getPrivate(), "BC"); } catch (InvalidKeyException e) { this.logger.error("InvalidKeyException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (NoSuchProviderException e) { this.logger.error("NoSuchProviderException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (SecurityException e) { this.logger.error("SecurityException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (SignatureException e) { this.logger.error("SignatureException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } }