gpt4 book ai didi

java - 将 java.security.PrivateKey 转换为字符串

转载 作者:行者123 更新时间:2023-11-29 04:28:47 25 4
gpt4 key购买 nike

PrivateKey 转换为 String 的方法有哪些

-----BEGIN PRIVATE KEY----------END PRIVATE KEY----- 可以作为私有(private)要上传到服务器的 key 文件。

实现是sun.security.rsa.RSAPrivateCrtKeyImplgetFormat()PKCS#8

最佳答案

我正在使用 Bouncy CaSTLe 1.57

您可以使用 org.bouncycaSTLe.openssl.jcajce.JcaPEMWriter 类:

StringWriter sw = new StringWriter();
JcaPEMWriter writer = new JcaPEMWriter(sw);
writer.writeObject(privateKey);
writer.close();
System.out.println(sw.getBuffer().toString());

输出将不完全符合您的要求(它有 RSA PRIVATE KEY 而不仅仅是 PRIVATE KEY):

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCLvmDlBlvtN+hJjGy46Q5EyFoJmpoReiXvOVx98BQblqWe7698
zwEJTf/9cfmg1M+qXhPqIPSWU61hPuh/GOZIfQAzAoGnCvZP4v8nGVhcYnnrxCQA
Pd7jdxPmQGbtvTW0cbJpBK44KknHAVdlwDZVqkweTE9c48jHXIHPNX6THwIDAQAB
AoGAczy/cp3X2Lst1tjyH1ow5g/CEAFp49eyyJ+o4kHEkyub0IEfWfDqjd3AqCQB
EtvrlDaYfY5HpF/ErljOKWFDJG8ealhGgZgLYhy7QCs2CUeUN1SkULvxcqLTjzD0
qQAfA1Xm3TYwIV4RB6TSbkr+iJeviz2FxcqjJWAyqh5bVAECQQDhI1/CppGMWPnN
pMBqK0kyk+yc00KB/xbyqzWVgV/de+5uU6YHmXwW29NdgrLt3+QXMwkLlDML7lBn
jawJ1KmfAkEAnuZPm7WYzsu/WvW6iMwBJDNiMC88Q6RPdlboY8mPNysewlAZubJ+
bd+l0E9P6Kdoi4mKqmWK91vRwambFaimgQJBAJPnF0va/ZdEBKfSag3VbfrqLvE/
4FtiZ4L4cvVKzt3EQvj7vwETFfA2bf7qk/2trjyHbJPMwlQ+NVgyPCkhKmUCQCMc
PsDoKmCfUqP1ogbyFNp75BlDhqxnlQtP/r913QhSpdRHwLdwglEi1s+lhsGgpBAZ
DyPBlig8CKgjItpxToECQGDvZdny/lwUOhlJaJYcpS4pKOG0Qzz5QyTdFjkzJlTo
tDElfWCoAc68YUU1N/XvHRr7P+2jLdh1+kjF28f0zlM=
-----END RSA PRIVATE KEY-----

如果你想要 BEGIN PRIVATE KEY(没有 RSA),我找不到直接的方法,所以你必须使用 replaceAll(不漂亮,但无论如何):

String pem = sw.getBuffer().toString().replaceAll("RSA PRIVATE", "PRIVATE");
System.out.println(pem);

输出:

-----BEGIN PRIVATE KEY-----
MIICXAIBAAKBgQCsbinJc7K/2Cn3YGo4ypiZijEH3sz2fXFKgmOAE/mZpkL3SoBc
iFGxYUTcE0qZ6Q/bakLdvPYj05VRr87sZ0Rosfa+BQr1AsDbcfJu/QcRVjE7IZON
yOBbYt40UFEUyht2uTQ7GpYRrLLj0GJ8K2QtFp0cX2mzsPrhOSuYSv9d8wIDAQAB
AoGAQfBm3nj2NFMPyV//fvRK4vxrv5y+OMzD1ECEmGgLHWztUvAUok4nH3QZBygB
cVYlED1UkMNARXcWNQTMVq8vA1D6VM5B4kmp8i6TK+grPEhnWpZRmBQxDv8D3Ury
FnoN9O11qDK1zd/XJhessxtiaLO+s1VwcsAeeBrQdFgEmwECQQDoTXzlCWeUBWNO
In/+iNUM8GgZxNGx8sK3WnmK/ZL0zSH2/3QZFaaKsyHZB/5fhAcubXkyw4GaEf6K
kd0yezkzAkEAvgUgmHNMJR9+LoDd+7P6/2emf3XXtlObu87yfmbhTE1sEw87U6Xh
QkRW8u7CcCceYy1BryduAMB5VdRPcuLIQQJAXf7sqGhTxusfMYB4Ne/79Q5ZsQOY
rd5Ct5oeUAUmr3NJaP4YZgYCq2CsM3sujEuJ9FlLjyTYjhT13/ABhumhTQJAXcSB
9TjQFnGX/rKw2AhUj7xCORuZuus/KkpQ93clLlX2QuF9USXGJsE6dt7DLDzhjedD
Rn+alNxmA6ilG/g1AQJBAIBoG4lLfjjU92NquiWvigggIKXC2EuAtvSF6+28MpQv
5sEWSjJ/mFM9vJcLjye1FXeUhrV9RUwqFqI6v7Firzc=
-----END PRIVATE KEY-----

您只需确保您的代码能够正确解析它(我不确定 Bouncy CaSTLe 是否在没有 RSA 的情况下解析它)。

关于java - 将 java.security.PrivateKey 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44784532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com