Java: Key类型和String之间的转换

Java: Converting between Key type and String

是否可以使用我生成的 public 密钥,将其转换为字符串,反向过程并再次将其用作密钥?

    generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);

    KeyPair keyPair = generator.generateKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

然后将其转换为字符串:

String public = someMethod(publicKey)

稍后再反转:

RSAPublicKey newPublicKey = someMethod(public)

您可以按如下方式将 Public 键转换为字符串。

String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());

然后可以将该字符串转换回 public 键,如下所示。

byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey2 = keyFactory.generatePublic(spec);