使用私有解密(publicEncrypt,privateDecrypt)解密时解密不正确的错误

时间:2018-12-14 07:24:04

标签: node.js cryptojs encryption-asymmetric

我是{J {3}}的NodeJ v10.14.2,用于创建非对称密钥对。 公钥和私钥已成功生成。之后,我想使用公共密钥对字符串进行加密,并希望使用私有密钥进行解密,但是在这种情况下,使用publicEncrypt可以很好地进行加密,但是之后使用privateDecrypt会给出错误的解密错误

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt.

这是我的代码

const { writeFileSync } = require('fs')
const { generateKeyPairSync, publicEncrypt, publicDecrypt, privateEncrypt, privateDecrypt } = require('crypto')
const passphrase = "1234567890"
function generateKeys() {
    const {
        privateKey,
        publicKey
    } = generateKeyPairSync('rsa', {
        modulusLength: 1024,
        publicKeyEncoding: {
            type: 'pkcs1',
            format: 'pem',
        },
        privateKeyEncoding: {
            type: 'pkcs1',
            format: 'pem',
            cipher: 'aes-256-cbc',
            passphrase,
        },
    })

    encryptD(publicKey, privateKey) 
}
let string = "Hello this string will be encrypted"
function encryptD(publicKey, privateKey)
{
    let buf = Buffer.from(string)
    console.log(buf)
    //<Buffer 48 65 6c 6c 6f 20 74 68 69 73 20 73 74 72 69 6e 67 20 77 69 6c 6c 20 62 65 20 65 6e 63 72 79 70 74 65 64>
    let encData = publicEncrypt(publicKey, buf)
    console.log("Encrypted Buffer", encData)
    //Encrypted Buffer <Buffer 1b bc fb ee ba c3 90 ca 87 37 3c 6a 0b 38 4b bd 92 8a 7c 1e 7c dd 06 26 58 5f 0b 35 f6 81 8f 55 58 03 db e2 a5 4d 2b d2 41 32 31 5e 6b 2a 62 e7 d6 b6 ... >
    let dncData = privateDecrypt(privateKey, encData)
    //Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
    console.log("decrypted ", dncData)
}
generateKeys()

我不知道我做错了什么 感谢您的帮助

0 个答案:

没有答案