Java源码示例:org.bouncycastle.asn1.x509.X509Extensions
示例1
private X509Certificate generateX509V3Certificate(final KeyPair keyPair,
final X500Principal subject,
final X500Principal issuer,
final Date notBefore,
final Date notAfter,
final BigInteger serialNumber,
final GeneralNames generalNames,
final boolean isCA) throws GeneralSecurityException {
X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
generator.setSerialNumber(serialNumber);
generator.setIssuerDN(issuer);
generator.setSubjectDN(subject);
generator.setNotBefore(notBefore);
generator.setNotAfter(notAfter);
generator.setPublicKey(keyPair.getPublic());
generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA));
generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160));
generator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
if (generalNames != null) {
generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames);
}
return generator.generateX509Certificate(keyPair.getPrivate(), SecurityUtil.getSecurityProvider());
}
示例2
/**
* 証明書署名要求のオブジェクトを作成する.
*
* @param keyPair キーペア
* @param commonName コモンネーム
* @param generalNames SANs
* @return 証明書署名要求のオブジェクト
* @throws GeneralSecurityException 作成に失敗した場合
*/
private static PKCS10CertificationRequest createCSR(final KeyPair keyPair,
final String commonName,
final GeneralNames generalNames) throws GeneralSecurityException {
final String signatureAlgorithm = "SHA256WithRSAEncryption";
final X500Principal principal = new X500Principal("CN=" + commonName + ", O=Device Connect Project, L=N/A, ST=N/A, C=JP");
DERSequence sanExtension= new DERSequence(new ASN1Encodable[] {
X509Extensions.SubjectAlternativeName,
new DEROctetString(generalNames)
});
DERSet extensions = new DERSet(new DERSequence(sanExtension));
DERSequence extensionRequest = new DERSequence(new ASN1Encodable[] {
PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
extensions
});
DERSet attributes = new DERSet(extensionRequest);
return new PKCS10CertificationRequest(
signatureAlgorithm,
principal,
keyPair.getPublic(),
attributes,
keyPair.getPrivate(),
SecurityUtil.getSecurityProvider());
}
示例3
private X509Certificate generateSignedCertificate(
PKCS10CertificationRequest csr) throws NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeyException,
CertificateParsingException, CertificateEncodingException,
SignatureException {
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(rootCert.getSubjectX500Principal());
Calendar c = Calendar.getInstance();
certGen.setNotBefore(c.getTime());
c.add(Calendar.YEAR, 1);
certGen.setNotAfter(c.getTime());
certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
certGen.setPublicKey(csr.getPublicKey("BC"));
certGen.setSignatureAlgorithm(ALGORITHM_SHA256_RSA);
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
new AuthorityKeyIdentifierStructure(rootCert.getPublicKey()));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
certGen.addExtension(X509Extensions.BasicConstraints, true,
new BasicConstraints(false));
certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
X509Certificate issuedCert = certGen.generate(rootPrivateKeyEntry
.getPrivateKey());
return issuedCert;
}
示例4
@SuppressWarnings("deprecation")
public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify) {
try {
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen.setSerialNumber(
serialNumber != null ? serialNumber :
// must be positive
BigInteger.valueOf(srand.nextLong()).abs().add(BigInteger.ONE));
v3CertGen.setIssuerDN(issuerPrincipal);
v3CertGen.setNotBefore(validityStartDate);
v3CertGen.setNotAfter(validityEndDate);
v3CertGen.setSignatureAlgorithm(signatureAlgorithm);
v3CertGen.setSubjectDN(subject);
v3CertGen.setPublicKey(keyToCertify);
JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false,
jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyToCertify));
if (numAllowedIntermediateCAs != null) {
// This certificate is for a CA that can issue certificates.
// See https://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/
v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numAllowedIntermediateCAs));
}
if (authorityKeyIdentifier!=null)
v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false,
authorityKeyIdentifier);
X509Certificate pkCertificate = v3CertGen.generate(issuerKey.getPrivate(), "BC");
return pkCertificate;
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}
示例5
private Map<DERObjectIdentifier, DEREncodable> createExtensions(PublicKey caPub, PublicKey userPub) throws IOException {
Map<DERObjectIdentifier, DEREncodable> ext = new HashMap<DERObjectIdentifier, DEREncodable>();
// not a CA
ext.put(X509Extensions.BasicConstraints, new BasicConstraints(false));
// obvious
ext.put(X509Extensions.KeyUsage, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature));
ext.put(X509Extensions.SubjectKeyIdentifier, getSubjectKeyInfo(userPub));
ext.put(X509Extensions.AuthorityKeyIdentifier, getAuthorityKeyIdentifier(caPub));
return ext;
}
示例6
@SuppressWarnings({ "deprecation", "resource" })
private BigInteger getCrlNumber(X509CRL crl) throws IOException {
byte[] crlNumberExtensionValue = crl.getExtensionValue(X509Extensions.CRLNumber.getId());
if (crlNumberExtensionValue == null) {
return null;
}
DEROctetString octetString = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(crlNumberExtensionValue)).readObject());
byte[] octets = octetString.getOctets();
DERInteger integer = (DERInteger) new ASN1InputStream(octets).readObject();
BigInteger crlNumber = integer.getPositiveValue();
return crlNumber;
}
示例7
/**
* Generates a new, self-signed X509 V3 certificate for a KeyPair.
*
* @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, "[email protected]")));
// This method is deprecated, but Android Eclair does not provide the
// generate() methods.
X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), SecurityUtil.getSecurityProvider());
return cert;
}
示例8
/**
* Creates a typical Certification Authority (CA) certificate.
* @param keyPair
* @throws SecurityException
* @throws InvalidKeyException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws CertificateException
*/
@SuppressWarnings("deprecation")
public static X509Certificate createTypicalMasterCert(final KeyPair keyPair)
throws SignatureException, InvalidKeyException, SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException
{
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
// BEGIN ODO CHANGES
// Added the Common Name "CN=CyberVillains CA" to the X.509 Distinguished Name below.
// This was added to work around a bug in iOS where certificates that lack Common Name's
// do not show up in the list of CA certificates found in Settings / General / About / Certificate Trust Settings.
// We needed this CA certificate to show up in this list so that we could manually trust it and therefore
// avoid the App Transport Security "Untrusted root certificate" errors.
X509Principal issuer=new X509Principal("CN=CyberVillains CA,OU=CyberVillains Certification Authority,O=CyberVillains.com,C=US");
// END ODO CHANGES
// Create
v3CertGen.setSerialNumber(BigInteger.valueOf(1));
v3CertGen.setIssuerDN(issuer);
v3CertGen.setSubjectDN(issuer);
//Set validity period
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ *(1000L * 60 * 60 * 24 * 30)));
v3CertGen.setNotAfter (new Date(System.currentTimeMillis() + 240 /* months */ *(1000L * 60 * 60 * 24 * 30)));
//Set signature algorithm & public key
v3CertGen.setPublicKey(keyPair.getPublic());
v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);
// Add typical extensions for signing cert
v3CertGen.addExtension(
X509Extensions.SubjectKeyIdentifier,
false,
new SubjectKeyIdentifierStructure(keyPair.getPublic()));
v3CertGen.addExtension(
X509Extensions.BasicConstraints,
true,
new BasicConstraints(0));
v3CertGen.addExtension(
X509Extensions.KeyUsage,
false,
new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign) );
DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector();
typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning));
typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown));
v3CertGen.addExtension(
X509Extensions.ExtendedKeyUsage,
false,
new DERSequence(typicalCAExtendedKeyUsages));
X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC");
cert.checkValidity(new Date());
cert.verify(keyPair.getPublic());
return cert;
}