Mô-đun crypto cung cấp chức năng mã hóa bao gồm một tập hợp các hàm băm của OpenSSL, HMAC, cipher, decipher, sign, và verify functions. Dưới đây là 1 ví dụ về cách mã hoá và giải mã thuật toán RSA nhé!
RSA là một thuật toánmật mã hóa khóa công khai. Đây là thuật toán đầu tiên phù hợp với việc tạo ra chữ ký điện tử đồng thời với việc mã hóa. Nó đánh dấu một sự tiến bộ vượt bậc của lĩnh vực mật mã học trong việc sử dụng khóa công cộng. RSA đang được sử dụng phổ biến trong thương mại điện tử và được cho là đảm bảo an toàn với điều kiện độ dài khóa đủ lớn.
Demo như sau:
Bước 1: Tạo cặp khoá private và public bằng câu lệnh. Mở Terminal lên và gõ lệnh sau:
openssl genrsa -out private.pem 2048 -sha256
Câu trên tạo ra cặp khóa RSA 2048 bit, mã hóa chúng bằng mật khẩu bạn cung cấp và ghi chúng vào một tệp private.pem. Sau đó dùng lệnh tiếp theo để tạo ra public key:
openssl rsa -in private.pem -outform PEM -pubout -out public.pem
Bước 2: Tạo 1 file encryption.js lên và code thôi:
const crypto = require("crypto");
const path = require("path");
const fs = require("fs");
const encryptStringWithRsaPublicKey = (toEncrypt, relativeOrAbsolutePathToPublicKey = './public.pem') => {
const absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
const publicKey = fs.readFileSync(absolutePath, "utf8");
const buffer = new Buffer(toEncrypt);
const encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
};
const decryptStringWithRsaPrivateKey = (toDecrypt, relativeOrAbsolutePathtoPrivateKey = './private.pem') => {
const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey);
const privateKey = fs.readFileSync(absolutePath, "utf8");
const buffer = new Buffer(toDecrypt, "base64");
const decrypted = crypto.privateDecrypt(privateKey, buffer);
return decrypted.toString("utf8");
};
module.exports = {
encryptStringWithRsaPublicKey,
decryptStringWithRsaPrivateKey
}
Vậy là ta đã có 1 hàm mã hoá bằng Public key và giải mã bằng Private key tương ứng.
Bước 3: tạo 1 file index.js chạy thử
const { encryptStringWithRsaPublicKey, decryptStringWithRsaPrivateKey } = require('./encryption');
const text = 'abcd1234';
const encrypt = encryptStringWithRsaPublicKey(text);
console.log('ENCRYPT text: ', encrypt);
const decrypt = decryptStringWithRsaPrivateKey(encrypt);
console.log('DECRYPT text: ', decrypt);
// output: ENCRYPT text: randomstring
// output: DECRYPT text: text