【发布时间】:2021-01-15 22:26:48
【问题描述】:
我需要在浏览器端加密数据并在 Rails 应用程序中使用 RSA 解密。
目前我在 JS 端使用 JSEncrypt 库,但我想用内置的 Web Crypto API 替换它。
我需要使用现有的 RSA 公钥进行加密,它是由 ruby OpenSSL 标准库生成的,以便与已经加密和保存的向后兼容。
我已设法将 RSA pubkey 作为 JWK 或 SPKI 导入 JS 并加密数据,但 Ruby 端未能解密。
JWK 导入和加密:
let pubKey = await crypto.subtle.importKey(
"jwk",
{
kid: "1",
kty: "RSA",
use: "enc",
key_ops: ["encrypt"],
alg: "RSA-OAEP-256",
e: pubKeyE,
n: pubKeyN
},
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: { name: "SHA-256" }
},
false,
["encrypt"]
);
console.log("pubKey imported");
let encryptedBuf = await crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
pubKey,
stringToArrayBuffer(content)
);
let encrypted = arrayBufferToString(encryptedBuf);
SPKI 导入和加密:
let pubKey = await crypto.subtle.importKey(
"spki",
stringToArrayBuffer(atob(pubKeyBase64)),
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: { name: "SHA-256" }
},
false,
["encrypt"]
);
console.log("pubKey imported");
let encryptedBuf = await crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
pubKey,
stringToArrayBuffer(content)
);
let encrypted = arrayBufferToString(encryptedBuf);
Ruby 公钥生成和解密:
rsa = OpenSSL::PKey::RSA.new(pem_private_key)
js_encrypted = Base64.decode64(js_encrypted_base64)
js_decrypted = rsa.private_decrypt(js_encrypted, OpenSSL::PKey::RSA::NO_PADDING)
在此处查看完整的可重现示例:
https://repl.it/@senid231/Web-Crypto-API-encrypt-with-imported-rsa-pubkey-as-JWK#script.js
https://repl.it/@senid231/Web-Crypto-API-encrypt-with-imported-rsa-pubkey-as-SPKI#script.js
https://repl.it/@senid231/Ruby-RSA-decrypt-data-encrypted-by-JS#main.rb
【问题讨论】:
-
可能的原因是不同的填充(WebCrypto API 端更现代的 OAEP 和 Ruby 端更旧的 PKCS#1 v1.5)。
-
我尝试了
OpenSSL::PKey::RSA允许的不同填充,但没有成功 -
@Topaco 感谢您的帮助。我已经设法在 ruby 端正确解密消息
标签: javascript ruby cryptography rsa webcrypto-api