i am trying to encrypt and decrypt a plain string using Rijndael-js
, crypto
and PKCS7-Padding
. But i am getting this error
const encrypted = encrypted
^
ReferenceError: Cannot access 'encrypted' before initialization
at decryptor (file:///data/data/com.termux/files/home/enc/main.js:19:23)
at file:///data/data/com.termux/files/home/enc/main.js:28:1
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
Node.js v18.10.0
when the decryptor
function is invoked. The encryptor
function is working perfectly fine and gives output but decryptor
gives the error.
Here is the code
import RijndaelManaged from 'rijndael-js'
import padder from 'pkcs7-padding'
import crypto from 'crypto'
let plainText, padded, key, iv, cipher, encrypted
const encryptor = async () => {
plainText = Buffer.from('Here is my plain text', 'utf8')
padded = padder.pad(plainText, 32)
key = crypto.randomBytes(32)
iv = crypto.randomBytes(32)
cipher = new RijndaelManaged(key, 'cbc')
encrypted = cipher.encrypt(padded, 256, iv)
console.log(encrypted)
}
encryptor()
const decryptor = () => {
const encrypted = encrypted
const key = key
const iv = iv
const decipher = new RijndaelManaged(key, 'cbc')
const decryptedPadded = decipher.decrypt(encrypted, 256, iv)
const decrypted = padder.unpad(decryptedPadded, 32)
const clearText = decrypted.toString('utf8')
console.log(clearText)
}
decryptor()