Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức crypto.privateDecrypt() trong Node.js


Phương thức crypto.privateDecrypt() dùng để giải mã dữ liệu bằng khóa riêng tư, dữ liệu này đã được mã hóa trước đó bằng khóa công khai tương ứng qua crypto.publicEncrypt().

Cú pháp

crypto.privateDecrypt(privateKey, buffer)

Tham số

  • key – Chứa 5 loại dữ liệu kiểu Object, String, Buffer, KeyObject:

    • oaepHash – Hàm hash cho OAEP padding và MGF1. Mặc định: 'sha1'.

    • oaepLabel – Giá trị cho OAEP padding. Không dùng label nếu không chỉ định.

    • padding – Padding trong crypto.constants.

  • buffer – Dữ liệu cần giải mã. Kiểu: string, TypedArray, Buffer, ArrayBuffer, DataView.

Ví dụ

Tạo file privateDecrypt.js và sao chép mã. Chạy lệnh:

node privateDecrypt.js

privateDecrypt.js

// Chương trình Node.js minh họa crypto.privateDecrypt()
// Import crypto và fs
const crypto = require('crypto');
const fs = require("fs");

// Đọc khóa công khai (có thể tạo bằng generateKeyPair())
publicKey = fs.readFileSync('public_key').toString();

// Văn bản cần mã hóa
var buf = Buffer.from('Hello TutorialsPoint', 'utf8');
// Mã hóa bằng khóa công khai
secretData = crypto.publicEncrypt(publicKey, buf);
// In dữ liệu mã hóa
console.log(secretData);

// Đọc khóa riêng
privateKey = fs.readFileSync('private_key').toString();
// Giải mã bằng khóa riêng
origData = crypto.privateDecrypt(privateKey, secretData);
console.log();

// In dữ liệu gốc dạng buffer
console.log(origData);

Kết quả

C:\home\node>> node privateDecrypt.js

Ví dụ 2

Ví dụ hoàn chỉnh tạo khóa, mã hóa, giải mã.

// Chương trình Node.js minh họa crypto.privateDecrypt()
// Import crypto và fs
const crypto = require('crypto');
const fs = require("fs");

// Hàm tạo file khóa
function generateKeyFiles() {
    const keyPair = crypto.generateKeyPairSync('rsa', {
        modulusLength: 530,
        publicKeyEncoding: {
            type: 'spki',
            format: 'pem'
        },
        privateKeyEncoding: {
            type: 'pkcs8',
            format: 'pem',
            cipher: 'aes-256-cbc',
            passphrase: ''
        }
    });
    fs.writeFileSync("public_key", keyPair.publicKey);
    fs.writeFileSync("private_key", keyPair.privateKey);
}

generateKeyFiles();

// Hàm mã hóa
function encryptString(plaintext, publicKeyFile) {
    const publicKey = fs.readFileSync(publicKeyFile, "utf8");
    const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(plaintext));
    return encrypted.toString("base64");
}

// Hàm giải mã với khóa riêng
function decryptString(ciphertext, privateKeyFile) {
    const privateKey = fs.readFileSync(privateKeyFile, "utf8");
    const decrypted = crypto.privateDecrypt({
        key: privateKey,
        passphrase: ''
    }, Buffer.from(ciphertext, "base64"));
    return decrypted.toString("utf8");
}

const plainText = "TutorialsPoint!";
const encrypted = encryptString(plainText, "./public_key");

console.log("Văn bản gốc:", plainText);
console.log();
console.log("Văn bản mã hóa: ", encrypted);
console.log();
console.log("Văn bản giải mã: ", decryptString(encrypted, "private_key"));

Kết quả

C:\home\node>> node privateDecrypt.js
Văn bản gốc: TutorialsPoint!
Văn bản mã hóa: AbSrqG4qFBG1q9KUBt8ddJxk9uNanOHXqY19N0mNHx0fm4M119dZVhcNrAvM8UaIRJvh7AsdWyjv1s cPA25KpeJuJQ==
Văn bản giải mã: TutorialsPoint!