将java.security.PrivateKey转换为String

时间:2017-06-27 15:41:50

标签: java base64 bouncycastle x509

使用

PrivateKey转换为String的方法有哪些?

-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----可用作要上传到服务器的私钥文件。

执行情况为sun.security.rsa.RSAPrivateCrtKeyImplgetFormat()PKCS#8

1 个答案:

答案 0 :(得分:3)

我正在使用 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的情况下解析它。)