英文:
Check if a base64 text is a valid RSA public key (4096)
问题
如何检查一个Base64文本是否为有效的RSA公钥格式(在Java中)。
==> 检查是否为Base64格式
==> 检查是否为有效的RSA 4096位密钥。
谢谢
英文:
How can i check if a base64 text is a valid RSA public key format (in java).
==> check that is in base64
==> check that is valid key of RSA 4096 bits.
Thank you
答案1
得分: 3
像这样的代码对你应该有效,请注意我添加的代码中的注释:
我参考了这个答案,并对代码进行了一些修改:https://stackoverflow.com/questions/10900643/how-can-i-construct-a-java-security-publickey-object-from-a-base64-encoded-strin
public static PublicKey getKey(String key){
try{
// 如果 base64 无效,你会在这里看到一个错误
byte[] byteKey = Base64.getDecoder().decode(key);
// 如果不是 RSA 公钥格式,你会在这里看到一个错误,类似于 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;
}
注意:以上是你提供的代码的中文翻译部分。如果你有任何其他问题或需要进一步的帮助,请随时提问。
英文:
Something like this should work for you, pay attention to the comments in the code that I added
I referred to this answer and made few modifications to the code: https://stackoverflow.com/questions/10900643/how-can-i-construct-a-java-security-publickey-object-from-a-base64-encoded-strin
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论