ตัวอย่างการเข้ารหัส และถอดรหัสด้วย NodeJS ( Encryption and Decryption By NodeJS )

 ความปลอดภัยในการทำ Application นับว่าเป็นเรื่องที่สำคัญอย่างยี่ง การทำระบบให้มีความปลอดภัยนั้นสิ่งหนึ่งที่ต้องมีนั้นคือ การเข้ารหัส และถอดรหัส (  Encryption and Decryption ) ในบทความนี้ จะแสดงตัวอย่างการเข้ารหัส และถอดรหัสด้วย NodeJS ดังนี้

รับเขียนโปรแกรม NodeJS

1. สร้าง folder sample_encrypt_decrypt ที่ D:\my_node_project\ ด้วยคำสั่ง  md sample_encrypt_decrypt
    สร้างไฟล์ package.json  ด้วยคำสั่ง npm init --y


2. สร้างไฟล์ index.js


3. สร้างไฟล์ encrypt_decrypt.js 

( ไฟล์เก็บ module การเข้ารหัส และถอดรหัส  - Encryption and Decryption )


4. พิมพ์ Code ในไฟล์ encrypt_decrypt.js

//เรียกใช้ crypto module
var crypto = require('crypto');
var algorithm = 'aes-256-ctr';
//กำหนด key สำหรับเข้ารหัส ต้องมีอย่างน้อย 32 ตัวอักษร
var ENCRYPTION_KEY = "XKJABbdAcXuk8/a8SKIwcA5owqSxHs7b";
var IV = "ddd280798e020d52";
 
// function  สำหรับเข้ารหัส
var encrypt=(text)=>{

    
    var iv=Buffer.from(IV, 'utf-8');
    let cipher = crypto.createCipheriv(algorithm, ENCRYPTION_KEY , iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return iv.toString('hex') + ':' + encrypted.toString('hex');
};

// function  สำหรับถอดรหัส
var decrypt=(text)=>{
        
    let textParts = text.split(':');
    let iv = Buffer.from(textParts.shift(), 'hex');
    let encryptedText = Buffer.from(textParts.join(':'), 'hex');
    let decipher = crypto.createDecipheriv(algorithm, ENCRYPTION_KEY, iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
};
//export module
module.exports = { encrypt, decrypt };

พิมพ์ Code ในไฟล์ index.js

//เรียก module ใน encrypt_decrypt.js
var encrypt_decrypt=require("./encrypt_decrypt.js");

var plain_text="My Plain_Text";
//เข้สรหัส ข้อมูลในตัวแปร plain_text ด้วยคำสั่ง encrypt_decrypt
var encrypted=encrypt_decrypt.encrypt(plain_text);
//แสดง Text ที่เข้ารหัสแล้ว
console.log("Encrypted :"+encrypted);
var decrypted=encrypt_decrypt.decrypt(encrypted);
//แสดง Text ถอดรหัสแล้ว
console.log("Decrypted :"+decrypted);


5. ทดลองรันโดยพิมพ์คำสั่ง node index ระบบจะแสดง ข้อความที่เข้ารหัสแล้ว
และข้อความที่เป็น Plain Text ดังรูป