java - 如何从字符串转换为 PublicKey?

我使用以下代码将公钥和私钥转换为字符串


KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String publicK = Base64.encodeBase64String(publicKey.getEncoded());
String privateK = Base64.encodeBase64String(privateKey.getEncoded());

现在我正在尝试将其转换回ad私钥


PublicKey publicDecoded = Base64.decodeBase64(publicK);

我收到无法从字节[]转换为公钥的错误。我尝试过


PublicKey publicDecoded = new SecretKeySpec(Base64.decodeBase64(publicK),"RSA");

这将导致如下所示的错误


java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Neither a public nor a private key

时间:

你不可以使用RSA的SecretKeySpec。

这应该可以:


byte[] publicBytes = Base64.decodeBase64(publicK);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);

,并解码专用PKCS8EncodedKeySpec

...