Web Crypto API:如何使用导入的RSA公钥加密数据并在Ruby中解密数据

问题描述

我需要在浏览器端加密数据,并使用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,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)),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

解决方法

由于Topaco的评论,我设法找到了如何在红宝石方面解密消息的方法。

ruby​​ OpenSSL标准库没有实现现代的RSA-OAEP,但是有一个gem可以添加此功能。

邮件已通过WEb加密API加密,并以SPKI格式导入了公钥。

let pubKey = await crypto.subtle.importKey(
    "spki",stringToArrayBuffer(atob(pubKeyBase64)),{
      name: "RSA-OAEP",modulusLength: 2048,publicExponent: new Uint8Array([1,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-oaep
require "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)