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

合金
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 ="...."; 成钥匙。我尝试生成密钥并获取编码的字节,并尝试将字节转换为字符串,如上面的代码所示,但我不确定我是否通过简单地将编码的字节转换为字符串来以正确的方式执行此操作。

克劳迪乌·沃内斯库
  1. 私钥/公钥字节:byte[] theBytes = key.getEncoded();
  2. 使用 new String(theBytes) 不太好,因为它使用默认的 Charset(基于 OS)。更好的是传递你想要的字符集(例如 UTF-8)并保持一致。
  3. 我建议有 Private/Public keys 的十六进制表示。有多种方法可以将 byte[] 转换为 HEX 字符串(Java 代码 To convert byte to Hexadecimal)。使用 HEX 格式也使密钥在某些 UI 中更易于阅读。例如:AA BB CC 22 24 C1 ..
  4. 其他选项是 Base64 格式,例如:Base64.getEncoder().encodeToString(theBytes)。(Java 8)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章