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 并获取编码字节,并尝试将字节转换为字符串,如上面的代码所示,但我不确定我是否通过简单地将编码字节转换为字符串来以正确的方式进行操作。
最佳答案
- 私钥/公钥字节: byte[] theBytes = key.getEncoded();
- 使用 new String(theBytes) 不太好,因为它使用默认的字符集(基于操作系统)。更好的是传递您想要的字符集(例如 UTF-8)并保持一致。
- 我建议使用十六进制表示私钥/公钥。有多种方法可以将 byte[] 转换为十六进制字符串 ( Java code To convert byte to Hexadecimal )。采用十六进制格式还使得 key 在某些 UI 中更易于阅读。例如:AA BB CC 22 24 C1 ..
- 其他选项是 Base64 格式,例如:Base64.getEncoder().encodeToString(theBytes)。 (Java 8)
关于java - 尝试将私钥和公钥转换为字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506163/