1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| const forge = require('node-forge');
function generateKeyPair(keySize = 2048) { const keyPair = forge.pki.rsa.generateKeyPair({ bits: keySize, e: 0x10001 }); return { privateKey: forge.pki.privateKeyToPem(keyPair.privateKey), publicKey: forge.pki.publicKeyToPem(keyPair.publicKey) }; }
function rsa2Sign(data, privateKey) { const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
const md = forge.md.sha256.create(); md.update(data, 'utf8');
const signature = privateKeyObj.sign(md);
return forge.util.encode64(signature); }
function rsa2Verify(data, signature, publicKey) { const publicKeyObj = forge.pki.publicKeyFromPem(publicKey);
const md = forge.md.sha256.create(); md.update(data, 'utf8');
const signatureBytes = forge.util.decode64(signature);
return publicKeyObj.verify(md.digest().bytes(), signatureBytes); }
(async () => { try { const { privateKey, publicKey } = generateKeyPair(); console.log('私钥:', privateKey); console.log('公钥:', publicKey);
const data = '这是要签名的数据';
const signature = rsa2Sign(data, privateKey); console.log('签名:', signature);
const isValid = rsa2Verify(data, signature, publicKey); console.log('签名验证结果:', isValid ? '有效' : '无效');
const tamperedData = '这是被篡改的数据'; const isTamperedValid = rsa2Verify(tamperedData, signature, publicKey); console.log('篡改后验证结果:', isTamperedValid ? '有效' : '无效'); } catch (err) { console.error('发生错误:', err); } })();
|