Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. const crypto = require('crypto')
  2. const ALGORITHM_NAME = 'aes-256-cbc'
  3. const ENCRYPT_KEY = 'e916e810f3858bffc8751581ca81a748'
  4. const IV_LENGTH = 16
  5. const NONCE_LENGTH = 4
  6.  
  7. const encryptString = (plainText) => {
  8. const nonce = crypto.randomBytes(NONCE_LENGTH)
  9. const iv = crypto.randomBytes(IV_LENGTH)
  10. const cipher = crypto.createCipheriv(ALGORITHM_NAME, ENCRYPT_KEY, iv)
  11. let encrypted = cipher.update(plainText, 'utf8', 'hex')
  12. encrypted += cipher.final('hex')
  13. const cipherText = Buffer.concat([iv, nonce, Buffer.from(encrypted, 'hex')])
  14. return cipherText.toString('hex')
  15. }
  16.  
  17. const decryptString = (cipherText) => {
  18. const cipherByte = Buffer.from(cipherText, 'hex')
  19. const iv = cipherByte.slice(0, IV_LENGTH)
  20. const originalText = cipherByte.slice(IV_LENGTH + NONCE_LENGTH, cipherByte.length)
  21. let decipher = crypto.createDecipheriv(ALGORITHM_NAME, ENCRYPT_KEY, iv)
  22. let decrypted = decipher.update(originalText.toString('hex'), 'hex', 'utf8')
  23. decrypted += decipher.final('utf8')
  24. return decrypted
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement