5

I am trying use the crypto.subtle.encrypt to encrypt some data and ran into trouble for the amount of data I can encrypt at a time. The maximum block size for a 2048-bit key using RSA-OAEP is 214Bytes, as indicated in links crypto.stackexchange.com and stackoverflow.com using the relation maxChunkSizeInBytes = keySizeInBytes – 42.

Using crypto.subtle.encrypt with a 2048-bit key and the RSA-OAEP algorithm, I am only able to encrypt 190 Bytes. Any amount below 190 Bytes works fine and any above 190 Bytes results in an error. I am not entirely sure the type of error (since I am unable to catch it), but I think its an OperationError , reference developer.mozilla.org.

In the TypeScript example shown here there are two data chunks d1 and d2 with sizes 190 Bytes and 214 Bytes respectively. The data block d1 encrypts fine, however, d2 does not.

const MSG_LEN_1 = 190;
const MSG_LEN_2 = 214;

const d1 = (window.crypto.getRandomValues(new Uint8Array(MSG_LEN_1))).buffer;
const d2 = (window.crypto.getRandomValues(new Uint8Array(MSG_LEN_2))).buffer;

let encData = async (data: ArrayBuffer) => {
    const key = await crypto.subtle.generateKey(
        {
            name: "RSA-OAEP",
            modulusLength: 2048,
            publicExponent: new Uint8Array([1, 0, 1]),
            hash: "SHA-256",
        },
        true,
        ["encrypt", "decrypt"]
    );
    const enc = await crypto.subtle.encrypt(
            {
              name: "RSA-OAEP"
            },
            key.publicKey,
            data
          );
    return enc;
};

encData(d1).then(
    (enc : ArrayBuffer) => {
        alert("Success working on d1");
    }
);

encData(d2).then(
    (enc : ArrayBuffer) => {
            alert("Success working on d2");
    }
);

On compiling and running the above TypeScript in Firefox and Chrome (by including in a simple html page) I notice an Uncaught (in promise) DOMException error in the developer console after the first alert.

Is there something I am missing when using crypto.subtle.encrypt or incorrectly using the RSA-OAEP algorithm?

  • May be I am using the wrong relationship, should I be using `maxChunkSizeInBytes = keySizeInBytes - hashSizeInBytes * 2 – 2` so for a 2048-bit key with a SHA-256 hash its `2048/8-256/8*2-2=190` Bytes ? – Nishit Joseph May 18 '19 at 07:53
  • Exactly, the size of a SHA-256 hash is 256 bits / 32 bytes – pedrofb May 18 '19 at 07:59

1 Answers1

3

Using the formula modulus size - 2 - 2*hash size, it is working properly for SHA256 (32 bytes). Seem you are applying SHA1 size(20 bytes)

  • SHA256: 256 - 2 - 2*32 = 190

  • SHA1: 256 - 2 - 2*20 = 214

pedrofb
  • 37,271
  • 5
  • 94
  • 142