为什么 WebCryptoAPI RSA-OAEP 加密函数无法使用给定密钥大小的预期最大块大小?

Nis*_*eph 5 encryption rsa webcrypto-api

我正在尝试使用crypto.subtle.encrypt来加密一些数据,但遇到了我一次可以加密的数据量的问题。使用 RSA-OAEP 的 2048 位密钥的最大块大小为 214 字节,如链接crypto.stackexchange.comstackoverflow.com 中使用关系所示maxChunkSizeInBytes = keySizeInBytes – 42

使用crypto.subtle.encrypt2048 位密钥和 RSA-OAEP 算法,我只能加密 190 字节。低于 190 字节的任何数量都可以正常工作,高于 190 字节的任何数量都会导致错误。我不完全确定错误的类型(因为我无法捕捉到它),但我认为它是一个OperationError参考developer.mozilla.org

在这里所示的例子打字稿有两个数据块d1d2与尺寸分别190个字节和214个字节。数据块d1加密得很好,但是d2 没有。

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");
    }
);
Run Code Online (Sandbox Code Playgroud)

在 Firefox 和 Chrome 中编译和运行上述 TypeScript(通过包含在一个简单的 html 页面中)时,我Uncaught (in promise) DOMException在第一个警报后注意到开发人员控制台中出现错误。

在使用crypto.subtle.encrypt或错误使用 RSA-OAEP 算法时,我是否遗漏了什么?

ped*_*ofb 3

使用公式modulus size - 2 - 2*hash size,它对于 SHA256(32 字节)可以正常工作。看来您正在应用 SHA1 大小(20 字节)

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

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