Why
When the client or the front end calls the API of the server to request the data, it is easy to intercept the user request / response data.
Such as fiddler, Wireshark etc.
This means that our data is not always in a safe environment.
So we need to encrypt out data when having data transmission.
For Module
Node official provide Crypto.js module, it offers a variety of encryption methods, such as RSA & AES etc.
The following are the use of methods provided by the Crypto.js module
RSA
- Prepare a pair of public and private keys and save in files.
- Ensure your key’s padding, it need to be same type when encrypt or decrypt.
- Padding
- An optional padding value defined in crypto.constants, which may be: crypto.constants.RSA_NO_PADDING, RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING.
- key can be an object or a string. If key is a string, it is treated as the key with no passphrase and will use RSA_PKCS1_OAEP_PADDING. Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.
Encrypt
- crypto.publicEncrypt(publicKey, buffer)1234567exports.publicEncrypt = (plainText, cb) => {let encryptBuff = crypto.publicEncrypt({key: this.getPublicKey(),padding: crypto.constants.RSA_PKCS1_PADDING}, Buffer.from(plainText));cb(encryptBuff.toString('base64'))}
- crypto.publicEncrypt(publicKey, buffer)
Decrypt
- crypto.privateDecrypt(privateKey, buffer)123456789exports.privateDecrypt = (encryptText, cb) => {let encryptBuff = Buffer.alloc(Constants.MAX_DECRYPT_BLOCK || 128);encryptBuff.write(encryptText, 'base64');let decryptBuff = crypto.privateDecrypt({key: this.getPrivateKey(),padding: crypto.constants.RSA_PKCS1_PADDING}, encryptBuff);cb(JSON.parse(decryptBuff.toString()));}
- crypto.privateDecrypt(privateKey, buffer)
Signature
- crypto.privateDecrypt(privateKey, buffer)1234567891011exports.signature = (plainText, cb) => {let sign = crypto.createSign('SHA256');try {sign.update(plainText);let privateKey = this.getPrivateKey();let result = sign.sign(privateKey, 'base64');cb(result)} catch (err) {console.log(err)}}
- crypto.privateDecrypt(privateKey, buffer)
- Block Encrypt
- crypto.publicEncrypt(publicKey, buffer)
- Block Decrypt
- crypto.publicEncrypt(publicKey, buffer)
AES
Save your secret key as a variable or in a file
Cipher
123456789101112131415161718const crypto = require('crypto');const Constants = require('./Constants')exports.cipher = (data, cb) => {const cipher = crypto.createCipher('aes192', Constants.AES_SECRET);let encrypted = cipher.update(data, 'utf8', 'base64');encrypted += cipher.final('base64');cb(encrypted)}```- Decipher``` bashexports.decipher = (cipherText, cb) => {const decipher = crypto.createDecipher('aes192', Constants.AES_SECRET);let decrypted = decipher.update(cipherText, 'base64', 'utf8');decrypted += decipher.final('utf8');cb(decrypted)}