【发布时间】:2020-08-18 09:06:54
【问题描述】:
我如何检查 base64 文本是否是有效的 RSA 公钥格式(在 java 中)。
==> 检查是否在 base64 中
==> 检查是否为 RSA 4096 位的有效密钥。
谢谢
【问题讨论】:
我如何检查 base64 文本是否是有效的 RSA 公钥格式(在 java 中)。
==> 检查是否在 base64 中
==> 检查是否为 RSA 4096 位的有效密钥。
谢谢
【问题讨论】:
这样的东西应该适合你,注意我添加的代码中的 cmets
我参考了这个答案并对代码做了一些修改:How can I construct a java.security.PublicKey object from a base64 encoded string?
public static PublicKey getKey(String key){
try{
//if base64 is invalid, you will see an error here
byte[] byteKey = Base64.getDecoder().decode(key);
//if it is not in RSA public key format, you will see error here as java.security.spec.InvalidKeySpecException
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(X509publicKey);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
【讨论】: