如何使用crypto.subtle加密/解密正确解密RSA-OAEP加密字符串?

问题描述 投票:0回答:1

我尝试使用 RSA 密钥对来加密和解密文件,并出于测试目的使用字符串。

它似乎正在正确生成密钥对(尽管一个轻微的危险信号是在尝试访问密钥时密钥的哈希对象似乎未定义),并且它似乎正在加密和解密,但完成的解密并没有返回原始字符串。

对于为什么会发生这种情况有什么想法吗?

这是我的代码:

const { subtle } = globalThis.crypto;

const publicExponent = new Uint8Array([1, 0, 1]);

async function generateRsaKeyPair(modulusLength = 2048, hash = 'SHA-256') {
    const { publicKey, privateKey } = await subtle.generateKey(
        {
            name: 'RSA-OAEP',
            modulusLength,
            publicExponent,
            hash,
        },
        true, // key is extractable
        ['encrypt', 'decrypt']
    );
    return { privateKey, publicKey };
}

function toBase64(buffer) {
    return Buffer.from(buffer).toString('base64');
}

async function testRsa() {
    const data = 'Hello, world!';

    const { publicKey, privateKey } = await generateRsaKeyPair();

    console.log('Public key: ', publicKey);
    console.log('Private key: ', privateKey);

    const encrypted = await subtle.encrypt('RSA-OAEP', publicKey, Buffer.from(data, 'utf-8'));
    console.log('Encrypted: ', toBase64(encrypted));

    const decrypted = await subtle.decrypt('RSA-OAEP', privateKey, encrypted)
    console.log('Decrypted: ', toBase64(decrypted));
}

testRsa();


CONSOLE LOGS:

Public key:  CryptoKey {
  type: 'public',
  extractable: true,
  algorithm: {
    name: 'RSA-OAEP',
    modulusLength: 2048,
    publicExponent: [Uint8Array],
    hash: [Object]
  },
  usages: [ 'encrypt' ]
}
Private key:  CryptoKey {
  type: 'private',
  extractable: true,
  algorithm: {
    name: 'RSA-OAEP',
    modulusLength: 2048,
    publicExponent: [Uint8Array],
    hash: [Object]
  },
  usages: [ 'decrypt' ]
}
Encrypted:  P1kTUPHV88QE3ogyHso/ExSVrX/HhIzXF3o4Zqslw3AbPPsA6WBtQtSotknLRG9P1aRjk5b44zhUdHq2eAE29uDmDR2SPFkC6GHfHEE9JX+Vtyz3L7T8t+tEFg3/8FJ+20pLPUUhVVN8+Y7Muw9nQt70kbIf9rVgSezB9COQUIb3FVyPCpp8nioFlKYfA6/2PYwJ0fTl/V4h1pCyq+au0RwTwVgRKR+HX1RwOxBpQOiFd7ufGkc6ItQSBVJfqSq3KgP+UH/2LAdoB6NTr+iPscK+Ep/LRNPBk12Bz6+haJNW5Dd0+LmbzIxOeIjlAbI+XzXt+bLsA87AQZHBwTMunw==
Decrypted:  SGVsbG8sIHdvcmxkIQ==

尝试使用 crypto.subtle RSA 加密/解密,没有得到解密的字符串

node.js encryption cryptography rsa subtlecrypto
1个回答
0
投票

返回的 ArrayBuffer 正如@Topaco所说是正确的,需要通过运行 Buffer.from(value).toString('utf8') 而不是 toBase64 将其转换为 UTF-8 字符串

© www.soinside.com 2019 - 2024. All rights reserved.