Encryption SublecryPto导入密钥对未处理错误:整数太大

Encryption SublecryPto导入密钥对未处理错误:整数太大,encryption,rsa,subtlecrypto,Encryption,Rsa,Subtlecrypto,我正在研究一个简单的概念验证,通过node.js和使用sublecrypto的浏览器通信导出和导入私钥和公钥。我安装了@special/webcrypto包,以保持前端和后端的一致性。第一部分只是生成和导出密钥,第二部分是我尝试导入密钥。代码如下: // GENERATE AND EXPORT KEYS const { publicKey, privateKey } = await crypto.subtle.generateKey( { name: 'RSA-OAEP',

我正在研究一个简单的概念验证,通过node.js和使用sublecrypto的浏览器通信导出和导入私钥和公钥。我安装了@special/webcrypto包,以保持前端和后端的一致性。第一部分只是生成和导出密钥,第二部分是我尝试导入密钥。代码如下:

// GENERATE AND EXPORT KEYS
const { publicKey, privateKey } = await crypto.subtle.generateKey(
  {
    name: 'RSA-OAEP',
    modulusLength: 2048,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: 'SHA-256',
  },
  true,
  ['encrypt', 'decrypt'],
);
const publicExport = await crypto.subtle.exportKey('spki', publicKey);
const privateExport = await crypto.subtle.exportKey('pkcs8', privateKey);

const pubExportedAsString = ab2str(publicExport);
const pubExportedAsBase64 = btoa(pubExportedAsString);
const publicKeyPem = `${pubExportedAsBase64}`;

const privExportedAsString = ab2str(privateExport);
const privExportedAsBase64 = btoa(privExportedAsString);
const privateKeyPem = `${privExportedAsBase64}`;

// IMPORT KEYS
const pubKeyImportedAsString = atob(publicKeyPem);
const pubKeyImportedAsArrayBuffer = str2ab(pubKeyImportedAsString);
const publicKeyImport = await crypto.subtle.importKey(
  'spki', pubKeyImportedAsArrayBuffer, { name: 'RSA-OAEP', hash: 'SHA-256' }, true, ['encrypt']
);

const privateKeyImportedAsString = atob(privateKeyPem);
const privateKeyImportedAsArrayBuffer = str2ab(privateKeyImportedAsString);
const privateKeyImport = await crypto.subtle.importKey(
  'pkcs8', privateKeyImportedAsArrayBuffer, { name: 'RSA-OAEP', hash: 'SHA-256' }, true, ['decrypt']
);

// HELPERS

const ab2str = (buffer: ArrayBuffer): string => new TextDecoder().decode(buffer);

const str2ab = (text: string): ArrayBuffer => new TextEncoder().encode(text);
导入密钥时会引发错误:

Unhandled error Error: Too big integer
我似乎看不出问题出在哪里,以及密钥编码和解码失败的原因。如果有人有任何线索或想法,那将非常有帮助:)

找到了答案(对于任何处于类似困境的人来说)。原来问题是ab2str和str2ab辅助函数,我被误导认为TextDecoder/TextEncoder可以正确处理这个用例的转换

将这些内容改写为以下内容解决了此问题

const ab2str = (buffer: ArrayBuffer) =>
  String.fromCharCode.apply(null, Array.from(new Uint8Array(buffer)));

const str2ab = (str: string): ArrayBuffer => {
  const buffer = new ArrayBuffer(str.length * 2);
  const bufferInterface = new Uint8Array(buffer);
  Array.from(str)
    .forEach((_, index: number) => bufferInterface[index] = str.charCodeAt(index));
  return buffer;
}