rsa pem java,使用java将RSA公钥导出到PEM String

本文档介绍了在Android环境中使用SpongyCastle库生成RSA公钥PEM字符串时遇到的问题。作者指出,与BouncyCastle库不同,SpongyCastle的PEMWriter类不直接支持PublicKey对象。通过查看源代码,发现可以将PemObject的类型参数从"RSAPUBLICKEY"更改为"PUBLICKEY"来解决此问题。最终代码示例展示了如何正确创建PEM字符串。
摘要由CSDN通过智能技术生成

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();

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.

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();

But for some reason the PEMWriter class does not exist in Spongy Castle

解决方案

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:

when calling writeObject it creates an instance of MiscPEMGenerator

MiscPEMGenerator then creates the PemObject by checking the type of the constructor's argument, the following is an excerpt from MiscPEMGenerator's source:

private PemObject createPemObject(Object o){

...

else if (o instanceof PublicKey)

{

type = "PUBLIC KEY";

encoding = ((PublicKey)o).getEncoded();

}

...

return new PemObject(type, encoding);

}

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值