本文为翻译和转载自 :
https://www.programcreek.com/...
以下是显示如何使用 org.bouncycastle.openssl.PEMWriter 的最佳投票示例。 这些示例是从开源项目中提取的。 您可以对您喜欢的示例进行投票,您的投票将在我们的系统中使用,以生成更多好的示例。
示例一 保存密钥和证书到文件中
/**
* 保存私钥和证书至文件
* @throws Exception
*/
protected void saveKeyPairAndCertificateToFile() throws Exception {
if(localPrivateKeyFile==null){
LOGGER.info("not saving private key nor certificate");
return;
}
//Encode in PEM format, the format prefered by openssl
// if(false){
// PEMWriter pemWriter=new PEMWriter(new FileWriter(localPrivateKeyFile));
// pemWriter.writeObject(localPrivateECKey);
// pemWriter.close();
// }
// else{
String keyText = "-----BEGIN EC PRIVATE KEY-----\n" +
Base64.encode(Unpooled.wrappedBuffer(localPrivateECKey.getEncoded()), true).toString(CharsetUtil.US_ASCII) +
"\n-----END EC PRIVATE KEY-----\n";
Files.write(keyText, localPrivateKeyFile, CharsetUtil.US_ASCII);
Files.write(localId.toString(), new File(localPrivateKeyFile.getParentFile(), "localPublic.hash"), CharsetUtil.US_ASCII);
// }
PEMWriter certificateWriter=new PEMWriter(new FileWriter(localCertificateFile));
certificateWriter.writeObject(cert);
certificateWriter.close();
LOGGER.info("Saved to "+localCertificateFile.getAbsolutePath());
}
示例二 :对私钥进行加密
/**
* 加密私钥
*
* @param key 私钥对象
* @param algorithm 密钥算法
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
*/
private void encryptedTest(PrivateKey key, ASN1ObjectIdentifier algorithm)
throws NoSuchProviderException, NoSuchAlgorithmException, IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut), "BC");
PKCS8Generator pkcs8 = new PKCS8Generator(key, algorithm, "BC");
pkcs8.setPassword("hello".toCharArray());
pWrt.writeObject(pkcs8);
pWrt.close();
PEMReader pRd = new PEMReader(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())), new PasswordFinder() {
public char[] getPassword() {
return "hello".toCharArray();
}
});
PrivateKey rdKey = (PrivateKey) pRd.readObject();
assertEquals(key, rdKey);
}
示例三 转换 rsa 的私钥为 pem 字符串
/**
* 转换 rsa的私钥为 pem 字符串
*
* @param rsaKeyPair RSA 类型keypair
* @return PEM string
*/
public static String getPEMStringFromRSAKeyPair(RSAKeyPair rsaKeyPair) {
StringWriter pemStrWriter = new StringWriter();
PEMWriter pemWriter = new PEMWriter(pemStrWriter);
try {
KeyPair keyPair = new KeyPair(rsaKeyPair.getPublic(), rsaKeyPair.getPrivate());
//pemWriter.writeObject(keyPair);
pemWriter.writeObject(keyPair.getPrivate());
//pemWriter.flush();
pemWriter.close();
} catch (IOException e) {
log.warning("Caught exception:" + e.getMessage());
return "";
}
return pemStrWriter.toString();
}
示例四 将 pem 数据对象转换成 pem 格式文件数据
/**
* 将pem 数据对象转换成 pem格式文件数据
* @param object
* @return
* @throws IOException
*/
public static byte[] toPem(Object object) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (PEMWriter writer = new PEMWriter(new OutputStreamWriter(outputStream))) {
writer.writeObject(object);
writer.flush();
return outputStream.toByteArray();
}
}
示例五 将多份 certificate 对象写入文件
private void writeCertificate(Certificate... certificates)
throws IOException {
final PEMWriter writer = new PEMWriter(new FileWriter(destfile));
for (final Certificate c : certificates) {
writer.writeObject(c);
}
writer.close();
}
示例六 将 X509Certificate 转换成 pem 格式数据
public String x509CertificateToPem(final X509Certificate cert) throws IOException {
final StringWriter sw = new StringWriter();
try (final PEMWriter pw = new PEMWriter(sw)) {
pw.writeObject(cert);
}
return sw.toString();
}
示例七 将 rsa 私钥对象转换为 PEM 格式数据
public String rsaPrivateKeyToPem(final PrivateKey key) throws IOException {
final PemObject pemObject = new PemObject(CCS_RSA_PRIVATE_KEY, key.getEncoded());
final StringWriter sw = new StringWriter();
try (final PEMWriter pw = new PEMWriter(sw)) {
pw.writeObject(pemObject);
}
return sw.toString();
}
示例八 将私钥、证书文件等转换为 PEM 数据
private static byte[] getPemBytes(Object... objects) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (PEMWriter pemWriter =
new PEMWriter(new OutputStreamWriter(byteArrayOutputStream, UTF_8))) {
for (Object object : objects) {
pemWriter.writeObject(object);
}
}
return byteArrayOutputStream.toByteArray();
}
示例九 将 X509Certificate 转换为 PEM 数据
private static String toPem(X509Certificate certificate) throws IOException {
StringWriter stringWriter = new StringWriter();
PEMWriter pemWriter = new PEMWriter(stringWriter, BouncyCastleProvider.PROVIDER_NAME);
pemWriter.writeObject(certificate);
pemWriter.close();
return stringWriter.toString();
}
示例十 将多个 证书数据 写入文件
private void writeCertificate(Certificate... certificates)
throws IOException {
final PEMWriter writer = new PEMWriter(new FileWriter(destfile));
for (final Certificate c : certificates) {
writer.writeObject(c);
}
writer.close();
}
示例十一 将 keyPair 转换成 Pem 格式
private String keyPairToString(KeyPair keyPair) {
StringWriter stringWriter = new StringWriter();
PEMWriter pemWriter = new PEMWriter(stringWriter);
try {
pemWriter.writeObject(keyPair);
pemWriter.flush();
pemWriter.close();
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException: "
+ e.getMessage(), e);
}
return stringWriter.getBuffer().toString();
}
示例十二 将私钥转换为 PEM 格式的 String
private static String getInPemFormat(PrivateKey privateKey)
throws IOException {
final StringWriter stringWriter = new StringWriter();
final PEMWriter pemWriter = new PEMWriter(stringWriter);
pemWriter.writeObject(privateKey);
pemWriter.flush();
pemWriter.close();
return stringWriter.toString();
}
示例十三 将 X509Certificate 转换为 PEM 格式的字符串
public String convertToPEMString(X509Certificate x509Cert) throws IOException {
StringWriter sw = new StringWriter();
try (PEMWriter pw = new PEMWriter(sw)) {
pw.writeObject(x509Cert);
}
return sw.toString();
}
示例十四 私钥的读写测试
private void doWriteReadTest(
PrivateKey akp,
String provider)
throws IOException
{
StringWriter sw = new StringWriter();
PEMWriter pw = new PEMWriter(sw, provider);
pw.writeObject(akp);
pw.close();
String data = sw.toString();
PEMReader pr = new PEMReader(new StringReader(data));
Object o = pr.readObject();
if (o == null || !(o instanceof KeyPair))
{
fail("Didn't find OpenSSL key");
}
KeyPair kp = (KeyPair) o;
PrivateKey privKey = kp.getPrivate();
if (!akp.equals(privKey))
{
fail("Failed to read back test");
}
}
示例十五 对私钥进行加密和解密测试
private void encryptedTestNew(PrivateKey key, ASN1ObjectIdentifier algorithm)
throws NoSuchProviderException, NoSuchAlgorithmException, IOException, OperatorCreationException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut), "BC");
JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(algorithm);
encryptorBuilder.setProvider("BC");
encryptorBuilder.setPasssword("hello".toCharArray());
PKCS8Generator pkcs8 = new JcaPKCS8Generator(key, encryptorBuilder.build());
pWrt.writeObject(pkcs8);
pWrt.close();
PEMReader pRd = new PEMReader(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())), new PasswordFinder()
{
public char[] getPassword()
{
return "hello".toCharArray();
}
});
PrivateKey rdKey = (PrivateKey)pRd.readObject();
assertEquals(key, rdKey);
}
示例十六 生成证书测试
public void test000GenerateCertificate() {
String cn = "www.example.it";
String keystoreFile = "guanxi_idp_cert.jks";
String keystorePassword = "changeit";
String privateKeyPassword = "changeit";
String privateKeyAlias = "www.example.it";
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyStore ks = null;
try {
ks = KeyStore.getInstance("JKS");
ks.load(null, null);
// KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair keypair = keyGen.generateKeyPair();
PrivateKey privkey = keypair.getPrivate();
PublicKey pubkey = keypair.getPublic();
Hashtable attrs = new Hashtable();
Vector ordering = new Vector();
ordering.add(X509Name.CN);
attrs.put(X509Name.CN, cn);
X509Name issuerDN = new X509Name(ordering, attrs);
X509Name subjectDN = new X509Name(ordering, attrs);
Date validFrom = new Date();
validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 10);
Date validTo = new Date();
validTo.setTime(cal.getTime().getTime());
// validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));
X509V3CertificateGenerator x509 = new X509V3CertificateGenerator();
//x509.setSignatureAlgorithm("SHA1withDSA");
x509.setSignatureAlgorithm("SHA256withRSA");
x509.setIssuerDN(issuerDN);
x509.setSubjectDN(subjectDN);
x509.setPublicKey(pubkey);
x509.setNotBefore(validFrom);
x509.setNotAfter(validTo);
x509.setSerialNumber(new BigInteger(128, new Random()));
X509Certificate[] cert = new X509Certificate[1];
cert[0] = x509.generate(privkey, "BC");
java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1];
chain[0] = cert[0];
ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert);
ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain);
ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray());
String IDP_RFC_CERT = "/tmp/guanxi_idp_cert.txt";
PEMWriter pemWriter = new PEMWriter(new FileWriter(IDP_RFC_CERT));
pemWriter.writeObject(cert[0]);
pemWriter.close();
} catch (Exception se) {
se.printStackTrace(System.err);
}
}
示例十七 获取 PKCS#10 PEM 字符串和加密的 PKCS#8 PEM 字符串
public String[] getPkcs10_Pkcs8_AsPemStrings(X500Name subject, String email, String pw)
throws IOException, NoSuchAlgorithmException,
NoSuchProviderException, OperatorCreationException, PKCSException {
// Create a PKCS10 cert signing request
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
PrivateKey priKey = kp.getPrivate();
// X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE);
// x500NameBld.addRDN(BCStyle.C, csrRequestValidationConfigParams.getCountryOID());
// x500NameBld.addRDN(BCStyle.O, csrRequestValidationConfigParams.getOrgNameOID());
// x500NameBld.addRDN(BCStyle.OU, ou);
// x500NameBld.addRDN(BCStyle.L, loc);
// x500NameBld.addRDN(BCStyle.CN, cn);
// X500Name subject = x500NameBld.build();
PKCS10CertificationRequestBuilder requestBuilder
= new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic());
ExtensionsGenerator extGen = new ExtensionsGenerator();
if(email != null){
extGen.addExtension(Extension.subjectAlternativeName, false,
new GeneralNames(new GeneralName(GeneralName.rfc822Name, email)));
}
requestBuilder.addAttribute(
PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
String sigName = "SHA1withRSA";
PKCS10CertificationRequest req1 = requestBuilder.build(
new JcaContentSignerBuilder(sigName).setProvider("BC").build(kp.getPrivate()));
if (req1.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kp.getPublic()))) {
//log.info(sigName + ": PKCS#10 request verified.");
} else {
//log.error(sigName + ": Failed verify check.");
throw new RuntimeException(sigName + ": Failed verify check.");
}
StringWriter writer = new StringWriter();
PEMWriter pemWrite = new PEMWriter(writer);
pemWrite.writeObject(req1);
pemWrite.close();
String csr = writer.toString();
JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder
= new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_3DES);
SecureRandom random = new SecureRandom();
encryptorBuilder.setRandom(random);
encryptorBuilder.setPasssword(pw.toCharArray());
OutputEncryptor oe = encryptorBuilder.build();
JcaPKCS8Generator pkcs8GeneratorEnc = new JcaPKCS8Generator(priKey, oe);
// Output encrypted private key pkcs8 PEM string (todo use later api)
PemObject pkcs8PemEnc = pkcs8GeneratorEnc.generate();
StringWriter writer2 = new StringWriter();
PEMWriter pemWrite2 = new PEMWriter(writer2);
pemWrite2.writeObject(pkcs8PemEnc);
pemWrite2.close();
String pkcs8StrEnc = writer2.toString();
String[] pems = new String[2];
pems[0] = csr;
pems[1] = pkcs8StrEnc;
return pems;
}
示例十八 测试用 ForgeJS 创建的三重 des PKCS8 私钥可以用 BC 解密。
public void decryptForgePkcs8PrivateKeyPem_PBEWithSHA1AndDESede() throws Exception {
// http://bouncy-castle.1462172.n4.nabble.com/Help-with-EncryptedPrivateKeyInfo-td1468363.html
// https://community.oracle.com/thread/1530354?start=0&tstart=0
Security.addProvider(new BouncyCastleProvider());
//PEMParser keyPemParser = new PEMParser(new StringReader(getPkcs8ForgePriKeyPem_PBEWithMD5AndDES()));
//String passwd = "1234567890";
PEMParser keyPemParser = new PEMParser(new StringReader(getPkcs8ForgePriKeyPem_EncryptedWithPBEWithSHA1AndDESede()));
String passwd = "password";
PemObject keyObj = keyPemParser.readPemObject();
byte[] keyBytes = keyObj.getContent();
EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(keyBytes);
// 1.2.840.113549.1.5.13 == PBEWithMD5AndDES
// 1.2.840.113549.1.12.1.3 == PBEWithSHA1AndDESede
String algName = encryptPKInfo.getAlgName();
String algId = encryptPKInfo.getAlgParameters().getAlgorithm();
assertEquals("PBEWithSHA1AndDESede", algName);
assertEquals("1.2.840.113549.1.12.1.3", algId);
assertEquals("1.2.840.113549.1.12.1.3", PKCS8Generator.PBE_SHA1_3DES.getId());
// Decrypt private key
Cipher cipher = Cipher.getInstance(algName);
PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd.toCharArray());
SecretKeyFactory secFac = SecretKeyFactory.getInstance(algName);
Key pbeKey = secFac.generateSecret(pbeKeySpec);
AlgorithmParameters algParams = encryptPKInfo.getAlgParameters();
cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
KeySpec pkcs8KeySpec = encryptPKInfo.getKeySpec(cipher);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey priKeyDecryptedBC = kf.generatePrivate(pkcs8KeySpec);
// Compare decrypted private key with a version that was decrypted using
// openssl and assert that they are the same.
JcaPKCS8Generator pkcs8GeneratorNoEnc = new JcaPKCS8Generator(priKeyDecryptedBC, null);
PemObject pkcs8PemDecryptedBC = pkcs8GeneratorNoEnc.generate();
StringWriter writer3 = new StringWriter();
PEMWriter pemWrite3 = new PEMWriter(writer3);
pemWrite3.writeObject(pkcs8PemDecryptedBC);
pemWrite3.close();
String pkcs8StrDecryptedBC = writer3.toString().trim().replaceAll("\\r\\n", "\n");;
String pkcs8StrDecryptedOpenSSL = getPkcs8ForgePriKeyPem_DecryptedWithOpenSSL().trim().replaceAll("\\r\\n", "\n");;
//System.out.println("["+pkcs8StrNoEncBC+"]");
//System.out.println("["+pkcs8StrNoEncOpenssL+"]");
assertTrue(pkcs8StrDecryptedBC.equals(pkcs8StrDecryptedOpenSSL));
}
示例十九 生成ECDSA 证书并存为P12格式 和pem格式
public static void main(String[] args)
throws Exception
{
if (args.length != 2)
{
System.err.println("Usage: GenTrustAnchorKeyStore keyStoreName keyStorePassword");
System.exit(1);
}
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ECDSA", "BC");
kpGen.initialize(new ECNamedCurveGenParameterSpec("secp256r1"));
KeyPair kp = kpGen.generateKeyPair();
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
builder.addRDN(BCStyle.C, "AU");
builder.addRDN(BCStyle.O, "Crypto Workshop Pty Ltd");
builder.addRDN(BCStyle.OU, "Ximix Node Test CA");
builder.addRDN(BCStyle.L, "Melbourne");
builder.addRDN(BCStyle.ST, "Victoria");
builder.addRDN(BCStyle.CN, "Trust Anchor");
Date startDate = new Date(System.currentTimeMillis() - 50000);
ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(kp.getPrivate());
X509v1CertificateBuilder certGen1 = new JcaX509v1CertificateBuilder(builder.build(), BigInteger.valueOf(1), startDate, new Date(System.currentTimeMillis() + 2 * YEAR),builder.build(), kp.getPublic());
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen1.build(sigGen));
KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
keyStore.load(null, null);
keyStore.setKeyEntry("trust", kp.getPrivate(), null, new Certificate[] { cert });
keyStore.store(new FileOutputStream(args[0] + ".p12"), args[1].toCharArray());
PEMWriter pWrt = new PEMWriter(new FileWriter(args[0] + ".pem"));
pWrt.writeObject(cert);
pWrt.close();
}