nodejs私钥加密公钥解密的一个例子
2024/03/01    
    公钥私钥生成网站 //https://www.metools.info/code/c81.html
    
    //nodejs公钥私钥生成方法
        let crypto = require('crypto');
    let {privateKey,publicKey} = crypto.generateKeyPairSync('rsa',{modulusLength:2408});
    console.log(privateKey.export({type:'pkcs1',format:'pem'}));
    console.log(publicKey.export({type:'pkcs1',format:'pem'}));
    //nodejs公钥私钥生成方法//结束
    
    //加解密开始
    let publicKey = `-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu336QqwOGw+RavP/6yad
GmxrNjKdWBE/tASABCDh0oZogr2neM1edyuRG3zuNzsMzcYeh2FXuZnflrmu0bYr
Bp/3+wRd/OQX8HYrbt/5MD8JoyY3Ya28mJzW8Kh6+Nby6ZN2OMz2Jjhu99FhsepK
l9g9HpV17lMId31h77L4V2lQ6K1Yf1JC09odXgiNrxhAZU/6lL4unV2sNVR8eB/M
YrXLQyiUDZEMtRHfb8OFB1vsPMsHLdpy/gKgKmstZsmMW6SasFszmLkOfRagBJoR
XEKSbUDCbeUp3q1ZCAjKGWFYUd0aBmcuisptOJABceVn2KGZ5eGZtef8soiex8zU
8y37JeyfPESLCylJGKqLVzvzJJGpWCbymrY3tVEfhqr2uBR1zgnVG0i9wdFOHdq3
hGZcmKQCsju/HrdxYUGqmsCIUl19Ct60rgDQc5aqFlwAg9C1vutn/TKvVIDfmXIy
KkB5lDNg8+dtxB6wklKw+17Z42el1yltaqIuTayblFKL5ZDDSfeb+bNDslzoah8K
5rGBmmCSM2OL598CWWHuPQIMRGaaD5gFGlWSIfZKbppcn/gSJKIu4Y7mnUchjw+2
4n5QnojXTfzjUnoISi1/n5QBQA+bX0lNQal4Kb0+72qQ892koPbndJpv5OIB97eh
C3rXnzLQnwG/UrAT/wFnMp0CAwEAAQ==
-----END PUBLIC KEY-----
    `
    let privateKey = `-----BEGIN PRIVATE KEY-----
MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS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6EJmQVfVx
ljqIAfXX7MsMyIBNpinIew3HLuwOb8cYkYu/rlPk5ycauAELzSGN+VhIspY3MdMh
Ka9moP+VIbjW8OovZfsi1Wt+YIwWLkhieDOO4sGK2CnT9inAkKXYAQSV8KDvklaQ
iTEOIiqA3n9VTjZcc0dFzfTYoNkxTPUPnncMJeyyha1GH6Xw8z+lO3ai6t1A7+zO
1I/uQ91uSKMkryNTLL5cXfp7bD4XPvWwp8qxQru4IoM6A3utB+zOhPxV6XQVaz/M
IYTAN1phC55mmWEE7e2eKBx4ifMs11cEmjm5U7+BAoIBAQCPWOJ7rywTAUA4JfLB
0jsjY9hCx9iQHr5wvUhk5/qxG2F+LADzrhDJotixjDK3VjkwE3nBYY+uJ/PNtniN
FChYC9qN1XnXJg5tRViabVtjP6WbcxA1qhYg0xMZbhrir4O4DITIqo4RqAfo8KCe
hKJ+2TkqlL1McHcFb28BA+490TTrj+D9rOPTxSmsN9cys0RnM0DwKD2qckCxwB2S
cHB4N7leZvaF/o89LaRriZA5cYii/CE0VMRnV9Po7NhjN9IDCP6NVOt2YJPpPVcj
hyU37xKZsdaRs0BKbvgHf6hiTPu0ePS9NGA7n/AyVBCPTeNkYN8qN/2sR45mJ3cq
LFdrAoIBAGBJtv2t2u7cpumvfSdl/invS33Zrgw1W8t4fPhIRO9s1SKUESWYgUvV
acb7/je/KMnH9HLlFanvlxPKQ3JGUD8wZ8JoTWNAW1lyOWnoW5g9bmRnzXNi14r6
kXM5TzmJmMiZcctOkDSIuAfyMCcLK9IGngzfakQSvfQNunCdRoqIvXNtFISrd/xe
WcEAByEvN3liRId8MIz3rtji5udpjDgEHtI2QKzdRODCEuuSx/nV6fz39GCTH1MD
At+bVhiiRddRutD7z3VCX+QF7tggkeK2Rbwlt+Vp3V5KfFY84ikXAWivBXcGU7zj
ClPeFWyiIv9+6ed8QhLyxI3UppW8xYI=
-----END PRIVATE KEY-----
    `
    //加密开始
    const crypto = require('crypto');
    const data = 'hello world';
    const encryptedData = crypto.privateEncrypt({
        key:privateKey,
        passphrase:""
    },Buffer.from(data));
    let encryptedDataBase64 = encryptedData.toString('base64');
    //公钥解密
    let decryptedData = crypto.publicDecrypt(publicKey,Buffer.from(encryptedDataBase64,'base64'));
    console.log(decryptedData.toString());

注意公钥私钥开头不能有空格,主体和‘

-----BEGIN PRIVATE KEY-----

’之间只有一个回车,不能存在空格