本文整理汇总了Java中org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder.addExtension方法的典型用法代码示例。如果您正苦于以下问题:Java JcaX509v3CertificateBuilder.addExtension方法的具体用法?Java JcaX509v3CertificateBuilder.addExtension怎么用?Java JcaX509v3CertificateBuilder.addExtension使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder
的用法示例。
在下文中一共展示了JcaX509v3CertificateBuilder.addExtension方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createSelfSignedSSLKeyPair
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
public static SSLKeyPair createSelfSignedSSLKeyPair(String commonsName, RSAPrivateKey caPrivateKey, RSAPublicKey caPublicKey) {
try {
BigInteger serial = BigInteger.valueOf(new Random().nextInt());
long end = System.currentTimeMillis() + DEFAULT_CERTIFICATE_DURATION_VALIDITY;
org.bouncycastle.asn1.x500.X500Name commonsX500Name = new org.bouncycastle.asn1.x500.X500Name(COMMON_NAME_ENTRY + commonsName);
JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(commonsX500Name, serial, new Date(), new Date(end), commonsX500Name, caPublicKey);
JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
certificateBuilder.addExtension(subjectKeyIdentifier, false, jcaX509ExtensionUtils.createSubjectKeyIdentifier(caPublicKey));
certificateBuilder.addExtension(basicConstraints, true, new BasicConstraints(true));
addASN1AndKeyUsageExtensions(certificateBuilder);
X509Certificate cert = verifyCertificate(caPrivateKey, caPublicKey, certificateBuilder);
return new SSLKeyPair(caPrivateKey, caPublicKey, new X509Certificate[]{cert});
} catch (NoSuchAlgorithmException | CertIOException | CertificateException | InvalidKeyException | OperatorCreationException | SignatureException | NoSuchProviderException e) {
throw new RuntimeException("Unable to generate SSL certificate for " + commonsName, e);
}
}
示例2: genCert
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
/**
* 动态生成服务器证书,并进行CA签授
*
* @param issuer 颁发机构
*/
public static X509Certificate genCert(String issuer, PrivateKey caPriKey, Date caNotBefore,
Date caNotAfter, PublicKey serverPubKey,
String... hosts) throws Exception {
/* String issuer = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=ProxyeeRoot";
String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + host;*/
//根据CA证书subject来动态生成目标服务器证书的issuer和subject
String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + hosts[0];
//doc from https://www.cryptoworkshop.com/guide/
JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(issuer),
//issue#3 修复ElementaryOS上证书不安全问题(serialNumber为1时证书会提示不安全),避免serialNumber冲突,采用时间戳+4位随机数生成
BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000),
caNotBefore,
caNotAfter,
new X500Name(subject),
serverPubKey);
//SAN扩展证书支持的域名,否则浏览器提示证书不安全
GeneralName[] generalNames = new GeneralName[hosts.length];
for (int i = 0; i < hosts.length; i++) {
generalNames[i] = new GeneralName(GeneralName.dNSName, hosts[i]);
}
GeneralNames subjectAltName = new GeneralNames(generalNames);
jv3Builder.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
//SHA256 用SHA1浏览器可能会提示证书不安全
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPriKey);
return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer));
}
示例3: generateCert
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
private X509CertificateObject generateCert(String keyName, KeyPair kp, boolean isCertAuthority,
PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException,
CertIOException, OperatorCreationException, CertificateException,
NoSuchAlgorithmException {
Calendar startDate = DateTimeUtils.calendar();
Calendar endDate = DateTimeUtils.calendar();
endDate.add(Calendar.YEAR, 100);
BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis());
X500Name issuer = new X500Name(
IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE));
JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer,
serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic());
JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
certGen.addExtension(Extension.subjectKeyIdentifier, false,
extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
certGen.addExtension(Extension.basicConstraints, false,
new BasicConstraints(isCertAuthority));
certGen.addExtension(Extension.authorityKeyIdentifier, false,
extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
if (isCertAuthority) {
certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
}
X509CertificateHolder cert = certGen.build(
new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey));
return new X509CertificateObject(cert.toASN1Structure());
}
示例4: addJcaX509Extension
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
private static JcaX509v3CertificateBuilder addJcaX509Extension(String commonsName, RSAPublicKey publicKey, X509Certificate issuerCertificate, long duration, boolean isCaCertificate) throws NoSuchAlgorithmException, CertIOException {
long end = System.currentTimeMillis() + duration;
BigInteger serial = BigInteger.valueOf(new SecureRandom(publicKey.getEncoded()).nextLong());
JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(new org.bouncycastle.asn1.x500.X500Name(issuerCertificate.getSubjectDN().getName()), serial, new Date(), new Date(end), new org.bouncycastle.asn1.x500.X500Name(COMMON_NAME_ENTRY + commonsName), publicKey);
JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
certificateBuilder.addExtension(subjectKeyIdentifier, false, jcaX509ExtensionUtils.createSubjectKeyIdentifier(publicKey));
certificateBuilder.addExtension(basicConstraints, isCaCertificate, new BasicConstraints(isCaCertificate));
return certificateBuilder;
}
示例5: addASN1AndKeyUsageExtensions
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
private static void addASN1AndKeyUsageExtensions(JcaX509v3CertificateBuilder certificateBuilder) throws CertIOException {
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));
KeyUsage keyUsage = new KeyUsage(keyCertSign | digitalSignature | keyEncipherment | dataEncipherment | cRLSign);
certificateBuilder.addExtension(Extension.keyUsage, false, keyUsage);
}
示例6: createCertificate
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
/**
* Creates a generic self-signed challenge {@link X509Certificate}. The certificate is
* valid for 7 days.
*
* @param keypair
* A domain {@link KeyPair} to be used for the challenge
* @param subject
* Subjects to create a certificate for
* @return Created certificate
*/
private static X509Certificate createCertificate(KeyPair keypair, String... subject) throws IOException {
final long now = System.currentTimeMillis();
final String signatureAlg = "SHA256withRSA";
try {
X500Name issuer = new X500Name("CN=acme.invalid");
BigInteger serial = BigInteger.valueOf(now);
Instant notBefore = Instant.ofEpochMilli(now);
Instant notAfter = notBefore.plus(Duration.ofDays(7));
JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
issuer, serial, Date.from(notBefore), Date.from(notAfter),
issuer, keypair.getPublic());
GeneralName[] gns = new GeneralName[subject.length];
for (int ix = 0; ix < subject.length; ix++) {
gns[ix] = new GeneralName(GeneralName.dNSName, subject[ix]);
}
certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns));
JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg);
byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert));
} catch (CertificateException | OperatorCreationException ex) {
throw new IOException(ex);
}
}
示例7: generateV3Certificate
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException {
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Signers name
X500Name issuerName = new X500Name(issuer);
// Subjects name - the same as we are self signed.
X500Name subjectName = new X500Name(issuer);
// Serial
BigInteger serial = new BigInteger(256, new SecureRandom());
// Not before
Date notBefore = new Date(System.currentTimeMillis() - 10000);
Date notAfter = new Date(expirationTime);
// Create the certificate - version 3
JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern();
builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes));
ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey);
X509CertificateHolder holder = builder.build(signer);
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);
return cert;
}
示例8: createPSSCert
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
private void createPSSCert(String algorithm)
throws Exception
{
KeyPair pair = generateLongFixedKeys();
PrivateKey privKey = pair.getPrivate();
PublicKey pubKey = pair.getPublic();
//
// distinguished name table.
//
X500NameBuilder builder = createStdBuilder();
//
// create base certificate - version 3
//
ContentSigner sigGen = new JcaContentSignerBuilder(algorithm).setProvider(BC).build(privKey);
JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),
new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey);
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true,
new X509KeyUsage(X509KeyUsage.encipherOnly));
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true,
new DERSequence(KeyPurposeId.anyExtendedKeyUsage));
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true,
new GeneralNames(new GeneralName(GeneralName.rfc822Name, "[email protected]")));
X509Certificate baseCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));
baseCert.verify(pubKey);
}
示例9: getSignedByIssuer
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
private X509Certificate getSignedByIssuer(
X509Certificate issuerCertificate,
PrivateKey issuerKey,
X500Principal issuerDn,
SubjectKeyIdentifier caSubjectKeyIdentifier,
KeyPair keyPair,
CertificateGenerationParameters params) throws Exception {
Instant now = timeProvider.getNow().toInstant();
BigInteger certificateSerialNumber = serialNumberGenerator.generate();
BigInteger caSerialNumber =
issuerCertificate != null ? issuerCertificate.getSerialNumber() : certificateSerialNumber;
final JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
issuerDn,
certificateSerialNumber,
Date.from(now),
Date.from(now.plus(Duration.ofDays(params.getDuration()))),
params.getX500Principal(),
keyPair.getPublic()
);
certificateBuilder.addExtension(
Extension.subjectKeyIdentifier,
false,
getSubjectKeyIdentifierFromKeyInfo(keyPair.getPublic()));
if (params.getAlternativeNames() != null) {
certificateBuilder
.addExtension(Extension.subjectAlternativeName, false, params.getAlternativeNames());
}
if (params.getKeyUsage() != null) {
certificateBuilder.addExtension(Extension.keyUsage, true, params.getKeyUsage());
}
if (params.getExtendedKeyUsage() != null) {
certificateBuilder
.addExtension(Extension.extendedKeyUsage, false, params.getExtendedKeyUsage());
}
if (caSubjectKeyIdentifier.getKeyIdentifier() != null) {
PublicKey issuerPublicKey = issuerCertificate != null ? issuerCertificate.getPublicKey() : keyPair.getPublic();
AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils
.createAuthorityKeyIdentifier(issuerPublicKey, issuerDn, caSerialNumber);
certificateBuilder
.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);
}
certificateBuilder
.addExtension(Extension.basicConstraints, true, new BasicConstraints(params.isCa()));
ContentSigner contentSigner = jcaContentSignerBuilder.build(issuerKey);
X509CertificateHolder holder = certificateBuilder.build(contentSigner);
return jcaX509CertificateConverter.getCertificate(holder);
}
示例10: beforeEach
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
@Before
public void beforeEach() throws Exception {
timeProvider = mock(DateTimeProvider.class);
now = Calendar.getInstance();
now.setTimeInMillis(1493066824);
later = (Calendar) now.clone();
later.add(Calendar.DAY_OF_YEAR, expectedDurationInDays);
when(timeProvider.getNow()).thenReturn(now);
serialNumberGenerator = mock(RandomSerialNumberGenerator.class);
when(serialNumberGenerator.generate()).thenReturn(BigInteger.valueOf(1337));
jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
generator = KeyPairGenerator
.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
generator.initialize(1024); // doesn't matter for testing
issuerKey = generator.generateKeyPair();
issuerDn = new X500Principal(caName);
generatedCertificateKeyPair = generator.generateKeyPair();
certificateGenerationParameters = defaultCertificateParameters();
subject = new SignedCertificateGenerator(timeProvider,
serialNumberGenerator,
jcaContentSignerBuilder,
jcaX509CertificateConverter,
getBouncyCastleProvider()
);
caSubjectKeyIdentifier =
jcaX509ExtensionUtils.createSubjectKeyIdentifier(issuerKey.getPublic());
caSerialNumber = BigInteger.valueOf(42l);
JcaX509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder(
issuerDn,
caSerialNumber,
Date.from(now.toInstant()),
Date.from(later.toInstant()),
issuerDn,
issuerKey.getPublic()
);
certificateAuthority = createCertificateAuthority(x509v3CertificateBuilder);
x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, caSubjectKeyIdentifier);
certificateAuthorityWithSubjectKeyId = createCertificateAuthority(x509v3CertificateBuilder);
expectedSubjectKeyIdentifier = certificateAuthorityWithSubjectKeyId.getExtensionValue(Extension.subjectKeyIdentifier.getId());
}
示例11: createX509V3Certificate
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
/**
* Creates an X509 version3 certificate.
*
* @param kp KeyPair that keeps the public and private keys for the new certificate.
* @param days time to live
* @param issuerBuilder IssuerDN builder
* @param subjectBuilder SubjectDN builder
* @param domain Domain of the server.
* @param signAlgoritm Signature algorithm. This can be either a name or an OID.
* @return X509 V3 Certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder,
X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
PublicKey pubKey = kp.getPublic();
PrivateKey privKey = kp.getPrivate();
byte[] serno = new byte[8];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed((new Date().getTime()));
random.nextBytes(serno);
BigInteger serial = (new java.math.BigInteger(serno)).abs();
X500Name issuerDN = issuerBuilder.build();
X500Name subjectDN = subjectBuilder.build();
// builder
JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( //
issuerDN, //
serial, //
new Date(), //
new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
subjectDN, //
pubKey //
);
// add subjectAlternativeName extension
boolean critical = subjectDN.getRDNs().length == 0;
ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[]{
new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String( domain )});
GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
GeneralNames subjectAltNames = new GeneralNames(new GeneralName[]{othernameGN});
certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
// add keyIdentifiers extensions
JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
try {
// build the certificate
ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
X509CertificateHolder cert = certBuilder.build(signer);
// verify the validity
if (!cert.isValidOn(new Date())) {
throw new GeneralSecurityException("Certificate validity not valid");
}
// verify the signature (self-signed)
ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
if (!cert.isSignatureValid(verifierProvider)) {
throw new GeneralSecurityException("Certificate signature not valid");
}
return new JcaX509CertificateConverter().getCertificate(cert);
} catch (OperatorCreationException | CertException e) {
throw new GeneralSecurityException(e);
}
}
示例12: generateUserCertificate
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; //导入方法依赖的package包/类
private X509Certificate generateUserCertificate(RSAPublicKey pubkey, boolean signature, String firstname, String lastname,
String idcode, String email, Date from, Date to) throws InvalidKeyException, ParseException, IOException, IllegalStateException,
NoSuchProviderException, NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException {
if (pubkey.getModulus().bitLength() != 2048) {
throw new IllegalArgumentException("Key must be 2048b RSA");
}
Date startDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2017-01-01");
Date endDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2017-12-31");
if (from != null) {
startDate = from;
}
if (to != null) {
endDate = to;
}
String template = "C=EE,O=ESTEID,OU=%s,CN=%s\\,%s\\,%s,SURNAME=%s,GIVENNAME=%s,SERIALNUMBER=%s";
// Normalize.
lastname = lastname.toUpperCase();
firstname = firstname.toUpperCase();
idcode = idcode.toUpperCase();
email = email.toLowerCase();
String subject = String.format(template, (signature ? "digital signature" : "authentication"), lastname, firstname, idcode,
lastname, firstname, idcode);
byte[] serialBytes = new byte[16];
random.nextBytes(serialBytes);
serialBytes[0] &= 0x7F; // Can't be negative
BigInteger serial = new BigInteger(serialBytes);
X509CertificateHolder real;
if (signature) {
real = getRealCert("sk-sign.pem");
} else {
real = getRealCert("sk-auth.pem");
}
log.trace("Generating from subject: " + real.getSubject());
log.trace("Generating subject: " + new X500Name(subject).toString());
JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(real.getIssuer(), serial, startDate, endDate, new X500Name(subject), pubkey);
@SuppressWarnings("unchecked")
List<ASN1ObjectIdentifier> list = real.getExtensionOIDs();
// Copy all extensions, except altName
for (ASN1ObjectIdentifier extoid : list) {
Extension ext = real.getExtension(extoid);
if (ext.getExtnId().equals(Extension.subjectAlternativeName)) {
// altName must be changed
builder.addExtension(ext.getExtnId(), ext.isCritical(), new GeneralNames(new GeneralName(GeneralName.rfc822Name, email)));
} else {
builder.copyAndAddExtension(ext.getExtnId(), ext.isCritical(), real);
}
}
// Generate cert
ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(BouncyCastleProvider.PROVIDER_NAME).build(esteidKey);
X509CertificateHolder cert = builder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(cert);
}