String 转 RSAPublicKey
时间: 2023-06-29 15:09:53 浏览: 190
以下是将 String 转换为 RSAPublicKey 的 Java 代码示例:
```
import java.security.spec.X509EncodedKeySpec;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.util.Base64;
// 这里的 publicKeyString 是要转换的 RSAPublicKey 的 Base64 编码字符串
String publicKeyString = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmqZ9H9q3n5J+8Wz8+z6rZgKl6d7eKfzC+e+uL4ZjZ3qDfXhE5n+2e9nC7sJiNQG0dk6cA5fG8PjzPmH9li5e7gW8Md+YysZQjWZpGyV7pHJqJQ4lQ7kxKLf6ggzCbISeP9fQ7wE5q4Rl2UUP6Jv5QfepxJ1z2a9PqHrs3H4eYk+7+7Cq+uQ1XO8JvXM5f4/1V1s2uFjZfA6J5mA6FaC8+P7f9tJ5sM8rmz1qzq3nL3BbC3RzK4X8xoX9X6P7xPp4B/bJlVvt16tgX+gjny3T59TJz9U7eZa5aO9CRRQsN9c4KntH1GyC1k7CQpZ6x1tQ+X1mzr0v4UuiJk1j2vDdowIDAQAB";
// 将 Base64 编码字符串转换为 byte 数组
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
// 构造 X509EncodedKeySpec 对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
// 获取 RSA KeyFactory 实例
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// 生成 RSAPublicKey 对象
PublicKey publicKey = keyFactory.generatePublic(keySpec);
// 强制转换为 RSAPublicKey
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
```
注意,这里的 `Base64` 类需要引入 `java.util.Base64` 包。
阅读全文