资讯专栏INFORMATION COLUMN

Java代码使用BC库中org.bouncycastle.openssl.PEMWriter 的 代

史占广 / 4023人阅读

摘要:本文为翻译和转载自以下是显示如何使用的最佳投票示例。这些示例是从开源项目中提取的。您可以对您喜欢的示例进行投票,您的投票将在我们的系统中使用,以生成更多好的示例。示例十九生成证书并存为格式和格式

本文为翻译和转载自 :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-----
" +
                Base64.encode(Unpooled.wrappedBuffer(localPrivateECKey.getEncoded()), true).toString(CharsetUtil.US_ASCII) +
                "
-----END EC PRIVATE KEY-----
";
        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("
", "
");;
    String pkcs8StrDecryptedOpenSSL = getPkcs8ForgePriKeyPem_DecryptedWithOpenSSL().trim().replaceAll("
", "
");;
    //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();
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72845.html

相关文章

  • 深度理解JVM-----运行时数据区域

    摘要:在之后,原来永久代的数据被分到了堆和元空间中。元空间存储类的元信息,静态变量和常量池等放入堆中。这样能在一些场景中显著提高性能,因为避免了在堆内存和堆外内存来回拷贝数据。 以下内容部分转载于: CS-Notes showImg(http://ww1.sinaimg.cn/large/005NT19Ply1g385uooqv9j30kd0slmyw.jpg); 程序计数器(Program...

    tuantuan 评论0 收藏0
  • Java GC

    摘要:对字节码文件进行解释执行,把字节码翻译成相关平台上的机器指令。使用命令可对字节码文件以及配置文件进行打包可对一个由多个字节码文件和配置文件等资源文件构成的项目进行打包。和不存在永久代这种说法。 Java技术体系 从广义上讲,Clojure、JRuby、Groovy等运行于Java虚拟机上的语言及其相关的程序都属于Java技术体系中的一员。如果仅从传统意义上来看,Sun官方所定义的Jav...

    justCoding 评论0 收藏0
  • Spring Cloud 参考文档(Spring Cloud Config Server)

    摘要:,这是标记配置文件集版本化的服务器端特性。要配置对称密钥,需要将设置为秘密字符串或使用环境变量将其排除在纯文本配置文件之外。 Spring Cloud Config Server Spring Cloud Config Server为外部配置提供基于HTTP资源的API(名称—值对或等效的YAML内容),通过使用@EnableConfigServer注解,服务器可嵌入Spring Bo...

    harryhappy 评论0 收藏0
  • 「Python 面试」第四次更新

    摘要:解决的办法在处理计算密集型任务时,使用多进程协程,发挥计算机多核的威力,而处理密集型,则可以使用多线程。至此,有关知识点的面试题就已告一段落,下次更新数据库,方面面试题。 showImg(https://segmentfault.com/img/bVbuYzy?w=3484&h=2480); 阅读本文大约需要 5 分钟。 15.说一说 GIL 前面有提到由于 Python 基于 C 语...

    hellowoody 评论0 收藏0

发表评论

0条评论

史占广

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<