java - 尝试将私钥和公钥转换为字符串格式

标签 java public-key-encryption encryption-symmetric

import java.security.*;

public class MyKeyGenerator {

    private KeyPairGenerator keyGen;
    private KeyPair pair;
    private PrivateKey privateKey;
    private PublicKey publicKey;
    private Context context;

    public MyKeyGenerator(Context context, int length)throws Exception{
        this.context =context;
        this.keyGen = KeyPairGenerator.getInstance("RSA");
        this.keyGen.initialize(length);
    }

    public void createKeys(){
        this.pair = this.keyGen.generateKeyPair();
        this.privateKey = pair.getPrivate();
        this.publicKey = pair.getPublic();
    }

    public PrivateKey getPrivateKey(){
        return this.privateKey;
    }

    public PublicKey getPublicKey(){
        return this.publicKey;
    }

    public  String getPrivateKeyStr(){
        byte b [] = this.getPrivateKey().getEncoded();
          return new String(b));
    }

    public  String getPublicKeyStr(){
        byte b [] = this.getPublicKey().getEncoded();
        return new String(b));
    }


}

您好,我已经搜索了如何转换或获取公钥或私钥的字符串表示形式,大多数答案都非常旧,仅用于如何转换 String pubKey ="....";变成一把 key 。 我尝试生成 key 并获取编码字节,并尝试将字节转换为字符串,如上面的代码所示,但我不确定我是否通过简单地将编码字节转换为字符串来以正确的方式进行操作。

最佳答案

  1. 私钥/公钥字节: byte[] theBytes = key.getEncoded();
  2. 使用 new String(theBytes) 不太好,因为它使用默认的字符集(基于操作系统)。更好的是传递您想要的字符集(例如 UTF-8)并保持一致。
  3. 我建议使用十六进制表示私钥/公钥。有多种方法可以将 byte[] 转换为十六进制字符串 ( Java code To convert byte to Hexadecimal )。采用十六进制格式还使得 key 在某些 UI 中更易于阅读。例如:AA BB CC 22 24 C1 ..
  4. 其他选项是 Base64 格式,例如:Base64.getEncoder().encodeToString(theBytes)。 (Java 8)

关于java - 尝试将私钥和公钥转换为字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506163/

相关文章:

javascript - 使用另一个字符串键 "encrypt"字符串的最简单方法?

Java浅拷贝数组

java - 调用时不支持获取 "405 - Request method ' GET'method=DELETE

amazon-web-services - 如何在 AWS 中管理非对称(公共(public)/私有(private)) key

android - iOS 5.0 : generated x509 rsa public key of size 2048 is 270 bytes instead of 294 bytes. 为什么?

c# - 使用 .NET 进行公钥加密并使用 Java 进行解密

加密库和 block 大小

java - 消息列表的 RSA 解密速度很慢

java - 安卓 : Making simple code. 干

java - 我对ScheduledThreadPoolExecutor.scheduleAtFixedRate和可能的并发感到困惑。为什么会有线程池?