Created
March 22, 2018 10:43
-
-
Save dima056359/c6321e3473f1d1f90649aaa36ef48522 to your computer and use it in GitHub Desktop.
Node.js DES encode/decode with prompt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
@@@ | |
@@@ npm install crypto-js js-base64 prompt | |
@@@ | |
*/ | |
// подключим либы для шифрования | |
// первым делом это crypto-js - набор библиотек для шифрования различными алгоритмами | |
var CryptoJS = require('crypto-js'); | |
// исходное сообщение шифруется первым делом в base64 | |
var Base64 = require('js-base64').Base64; | |
// библиотека для интерактивного опроса пользователя | |
var prompt = require('prompt'); | |
// запускаем опрос пользователя | |
// в данном случае программа спросит исходное сообщение, которое надо зашифровать | |
prompt.start(); | |
// получаем клавиатурный ввод пользователя и запоминаем в переменную plainText | |
prompt.get(['plainText'], function (err, result) { | |
// | |
// покажем результаты | |
// | |
//console.log(' text to encrypt: ' + result.plainText); | |
console.log("Plain text: ", result.plainText); | |
// зашифруем в base64 | |
var base64Coded = Base64.encode(result.plainText); | |
console.log("Base64 coded text: ", base64Coded); | |
// шифруем ключом | |
// TODO: генерировать ключ рандомно? окей, псевдорандомно, да | |
var encrypted = encryptDesCbcPkcs7Padding(base64Coded, "12345678"); | |
//console.log("Encrypted: ", encrypted); | |
var finalEncrypted = CryptoJS.enc.Base64.stringify(encrypted.ciphertext); | |
console.log("Final encrypted: ", finalEncrypted); | |
var base64Decoded = CryptoJS.enc.Base64.parse(finalEncrypted); | |
//console.log("Base64 decoded", base64Decoded); | |
var decrypted = decryptDesCbcPkcs7Padding(base64Decoded, "12345678"); | |
//console.log("Decrypted: ", decrypted); | |
var finalDecrypted = CryptoJS.enc.Base64.parse(decrypted.toString(CryptoJS.enc.Utf8)).toString(CryptoJS.enc.Utf8); | |
console.log("Final decrypted: ", finalDecrypted); | |
}); | |
function decryptDesCbcPkcs7Padding(message, key) { | |
var keyWords = CryptoJS.enc.Utf8.parse(key); | |
var ivWords = CryptoJS.lib.WordArray.create([0, 0]); | |
var decrypted = CryptoJS.DES.decrypt({ciphertext: message}, keyWords, { iv: ivWords }); | |
return decrypted.toString(CryptoJS.enc.Utf8); | |
} | |
function encryptDesCbcPkcs7Padding(message, key) { | |
var keyWords = CryptoJS.enc.Utf8.parse(key); | |
var ivWords = CryptoJS.lib.WordArray.create([0, 0]); | |
var encrypted = CryptoJS.DES.encrypt(message, keyWords, { iv: ivWords}); | |
return encrypted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment