Preface
I just answered the question "Asymmetric decryption error" asked by a brother in SegmentFault. This is a security application, and there should be many people who encounter the same problem. Based on the answered questions, I will briefly summarize it here.
For theoretical knowledge of asymmetric encryption, you can refer to the author's previous article "NODEJS Advanced: Theoretical Chapter of CRYPTO Module".
The complete code can be found in "Nodejs Learning Notes", and everyone is also welcome to follow Programmer Xiaoka's GitHub.
Encryption and decryption methods
In the module responsible for security is crypto. In asymmetric encryption, the corresponding APIs of public key encryption, private key decryption, and encryption and decryption are as follows.
Encryption function:
(key, buffer)
Decryption function:
(privateKey, buffer)
Beginner examples
Assume that there is the following
// const crypto = require('crypto'); // Encryption method = (data, key) => { // Note that the second parameter is the Buffer type return (key, (data)); }; // Decryption method = (encrypted, key) => { // Note that encrypted is Buffer type return (key, encrypted); };
Test code:
const utils = require('./utils'); const keys = require('./keys'); const plainText = 'Hello, I am Xiaoka, programmer'; const crypted = (plainText, ); // Encryptionconst decrypted = (crypted, ); // Decrypt(()); // Hello,I'm a programmer
Attach the public and private keys:
= `-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDFWnl8fChyKI/Tgo1ILB+IlGr8ZECKnnO8XRDwttBbf5EmG0qV 8gs0aGkh649rb75I+tMu2JSNuVj61CncL/7Ct2kAZ6CZZo1vYgtzhlFnxd4V7Ra+ aIwLZaXT/h3eE+/cFsL4VAJI5wXh4Mq4Vtu7uEjeogAOgXACaIqiFyrk3wIDAQAB AoGBAKdrunYlqfY2fNUVAqAAdnvaVOxqa+psw4g/d3iNzjJhBRTLwDl2TZUXImEZ QeEFueqVhoROTa/xVg/r3tshiD/QC71EfmPVBjBQJJIvJUbjtZJ/O+L2WxqzSvqe wzYaTm6Te3kZeG/cULNMIL+xU7XsUmslbGPAurYmHA1jNKFpAkEA48aUogSv8VFn R2QuYmilz20LkCzffK2aq2+9iSz1ZjCvo+iuFt71Y3+etWomzcZCuJ5sn0w7lcSx nqyzCFDspQJBAN3O2VdQF3gua0Q5VHmK9AvsoXLmCfRa1RiKuF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