Last active
          September 15, 2025 19:37 
        
      - 
      
 - 
        
Save montanaflynn/f0bd4c1fe58e28ce4d520bd1b84d2291 to your computer and use it in GitHub Desktop.  
    Encrypt and decrypt text using AES with a shared key in nodejs
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | const crypto = require('crypto'); | |
| const password = 'password'; | |
| function encrypt(password, text) { | |
| const algorithm = 'aes-256-ctr'; | |
| const key = Buffer.concat([Buffer.from(password), Buffer.alloc(32)], 32); | |
| const iv = crypto.randomBytes(16); | |
| const cipher = crypto.createCipheriv(algorithm, key, iv); | |
| let encrypted = cipher.update(text); | |
| encrypted = Buffer.concat([encrypted, cipher.final()]); | |
| return iv.toString('hex') + encrypted.toString('hex'); | |
| } | |
| function decrypt(password, text) { | |
| const algorithm = 'aes-256-ctr'; | |
| const key = Buffer.concat([Buffer.from(password), Buffer.alloc(32)], 32); | |
| const iv = Buffer.from(text.substring(0, 32), 'hex'); | |
| const encryptedText = Buffer.from(text.substring(32), 'hex'); | |
| const decipher = crypto.createDecipheriv(algorithm, key, iv); | |
| let decrypted = decipher.update(encryptedText); | |
| decrypted = Buffer.concat([decrypted, decipher.final()]); | |
| return decrypted.toString(); | |
| } | |
| const encryptedText = encrypt(password, 'Montana Flynn') | |
| const decryptedText = decrypt(password, encryptedText) | |
| console.log(encryptedText) | |
| // 792bc3507021447de9a232696e92d359 | |
| console.log(decryptedText) | |
| // Montana Flynn | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment