我需要在浏览器端加密数据,并使用RSA在Rails应用程序中解密它。
目前我在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
发布于 2020-09-30 22:55:29
多亏了Topaco comment,我找到了如何在Ruby端解密消息。
ruby OpenSSL标准库没有实现现代的RSA-OAEP,但是有一个gem,可以添加这个功能。
消息由WEb Crypto API加密,公钥以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);https://github.com/terashi58/openssl-oaep
$ gem install openssl-oaeprequire "openssl"
require "openssl/oaep"
require "base64"
rsa = OpenSSL::PKey::RSA.new(pem_private_key)
js_encrypted = Base64.decode64(js_encrypted_base64)
js_decrypted = rsa.private_decrypt_oaep(js_encrypted, '', OpenSSL::Digest::SHA256)https://stackoverflow.com/questions/64134353
复制相似问题