使用java将RSA公钥导出到PEM String [英] Export RSA public key to PEM String using java
问题描述
所以我使用Spongy Castle(Android)为RSA公钥生成PEM编码字符串,该字符串将上传到服务器。
这就是我目前正在做的事情:
So I'm using Spongy Castle (Android) to generate a PEM encoded string for an RSA public key that will be uploaded to a server. This is what I'm currently doing:
PublicKey publicKey = keyPair.getPublic();
StringWriter writer = new StringWriter();
PemWriter pemWriter = new PemWriter(writer);
pemWriter.writeObject(new PemObject("RSA PUBLIC KEY", publicKey.getEncoded()));
pemWriter.flush();
pemWriter.close();
return writer.toString();
现在你可能会说我不知道如何构建 PemObject
或者如果有更简单的方法可以做到这一点。
Now as you can probably tell I'm not sure how to construct the PemObject
or if there is an easier way to do this.
使用Bouncy Case时,我曾经这样做过这样的
When using Bouncy Case I used to do this like this
StringWriter writer = new StringWriter();
PEMWriter pemWriter = new PEMWriter(writer);
pemWriter.writeObject(keyPair.getPublic());
pemWriter.flush();
pemWriter.close();
return writer.toString();
但由于某种原因,Spongy Castle中不存在PEMWriter类
But for some reason the PEMWriter class does not exist in Spongy Castle
推荐答案
那么这可能不是最聪明的方式(或者可能是?),但是在检查了的来源之后PEMWriter
这个类基本上是这样做的:
Ok So this is probably not the smartest way (or maybe it is?) to do it, but after checking out the sources for PEMWriter
this class basically does this under the hood:
- 当调用
writeObject
它创建一个MiscPEMGenerator的实例
-
MiscPEMGenerator
然后通过检查构造函数参数的类型创建PemObject
,以下是MiscPEMGenerator
的摘录来源:
- when calling
writeObject
it creates an instance ofMiscPEMGenerator
MiscPEMGenerator
then creates thePemObject
by checking the type of the constructor's argument, the following is an excerpt fromMiscPEMGenerator
's source:
private PemObject createPemObject(Object o){
...
else if (o instanceof PublicKey)
{
type = "PUBLIC KEY";
encoding = ((PublicKey)o).getEncoded();
}
...
return new PemObject(type, encoding);
}
所以可以从 MiscPEMGenerator
代码看,我唯一要改变的是从RSA PUBLIC KEY到PUBLIC KEY的类型参数。这是最终代码。
So as can be seen from the MiscPEMGenerator
code the only thing I had to change was the type parameter from "RSA PUBLIC KEY" to just "PUBLIC KEY". Here is the final code.
PublicKey publicKey = keyPair.getPublic();
StringWriter writer = new StringWriter();
PemWriter pemWriter = new PemWriter(writer);
pemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
pemWriter.flush();
pemWriter.close();
return writer.toString();
这篇关于使用java将RSA公钥导出到PEM String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!