我正在使用AngularJS应用程序中用Java开发的服务。此服务返回RSA公钥的字节。我需要通过JavaScript中的字节装入密钥。总而言之,我需要在JavaScript中用Java完成以下操作:
public static PublicKey loadPublicKey(String stored){
byte[] data = Base64.decode(stored);
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePublic(spec);
}
有人能帮助我吗?
答案 0 :(得分:3)
您可以使用标准javascript WebCryptographyApi 导入公钥进行加密或验证签名。您需要根据预期的密钥用法设置算法和允许的操作。
<强>加密强>
//Convert the public key in base 64 (DER encoded) to array buffer
var publicKeyAB = str2ab(atob(publicKeyB64));
//import key to encrypt with RSA-OAEP
crypto.subtle.importKey(
"spki",
publicKeyAB,
{ name: "RSA-OAEP", hash: {name: "SHA-256"}},
false,
["encrypt"])
.then(function(key){
//do something with the key
}).catch(function(err) {
console.log(err );
});
验证签名
//Convert the public key in base 64 (DER encoded) to array buffer
var publicKeyAB = str2ab(atob(publicKeyB64));
//import the key to verify RSA signature with SHA 256
crypto.subtle.importKey(
"spki",
publicKeyAB,
{name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }},
false,
["verify"])
.then(function(key){
//do something with the key
}).catch(function(err) {
console.log(err );
});
效用函数
function str2ab(str) {
var arrBuff = new ArrayBuffer(str.length);
var bytes = new Uint8Array(arrBuff);
for (var iii = 0; iii < str.length; iii++) {
bytes[iii] = str.charCodeAt(iii);
}
return bytes;
}
查看更多示例here