API Web Crypto: como criptografar dados com chave pública RSA importada e descriptografar dados em Ruby

Sep 30 2020

Preciso criptografar dados no navegador e descriptografá-los no aplicativo Rails usando RSA.

Atualmente estou usando a JSEncryptbiblioteca no lado JS, mas quero substituí-la pela API Web Crypto integrada.

Preciso usar a chave pública RSA existente para criptografia, que foi gerada pela OpenSSLbiblioteca padrão ruby para compatibilidade com versões anteriores com aquela já criptografada e salva.

Consegui importar pubkey RSA para JS como JWK ou SPKI e criptografar dados, mas o lado Ruby não conseguiu descriptografá-lo.

Importação e criptografia 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);

Importação e criptografia 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);

Geração e descriptografia de chave pública 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)

veja exemplos reproduzíveis completos aqui:

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

Respostas

1 Senid Sep 30 2020 at 21:55

Graças ao comentário do Topaco , consegui descobrir como descriptografar a mensagem no lado rubi.

Biblioteca padrão ruby ​​OpenSSL não implementa moderno RSA-OAEP, mas há uma jóia, que pode adicionar esta funcionalidade.

A mensagem foi criptografada por WEb Crypto API com chave pública importada no formato 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-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)