Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why WebCryptoAPI RSA-OAEP encrypt function is unable to use the expected maximum chunk size for a given key size?

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?

like image 936
Nishit Joseph Avatar asked Oct 16 '22 15:10

Nishit Joseph


1 Answers

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

like image 96
pedrofb Avatar answered Oct 21 '22 06:10

pedrofb