Crypto.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <template>
  2. <main class="h-full">
  3. <UnderConstruction />
  4. </main>
  5. </template>
  6. <script>
  7. /* Import modules. */
  8. import crypto from 'crypto'
  9. export default {
  10. data: () => {
  11. return {
  12. //
  13. }
  14. },
  15. computed: {
  16. //
  17. },
  18. methods: {
  19. //
  20. },
  21. created: async function () {
  22. const algorithm = 'aes-256-cbc'
  23. const key = crypto.randomBytes(32)
  24. const iv = crypto.randomBytes(16)
  25. function encrypt (text) {
  26. const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv)
  27. let encrypted = cipher.update(text)
  28. encrypted = Buffer.concat([encrypted, cipher.final()])
  29. return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') }
  30. }
  31. function decrypt(text) {
  32. const iv = Buffer.from(text.iv, 'hex')
  33. const encryptedText = Buffer.from(text.encryptedData, 'hex')
  34. const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv)
  35. let decrypted = decipher.update(encryptedText)
  36. decrypted = Buffer.concat([decrypted, decipher.final()])
  37. return decrypted
  38. }
  39. const plaintext = 'Some serious stuff'
  40. console.log('\nPLAINTEXT', plaintext)
  41. const json = {
  42. // key,
  43. // iv,
  44. plaintext
  45. }
  46. console.log('\nJSON', json)
  47. const data = JSON.stringify(json)
  48. console.log('\nDATA', data)
  49. const buf = Buffer.from(data, 'utf-8')
  50. console.log('\nBUFFER', buf.length, buf)
  51. const hw = encrypt(buf)
  52. console.log('\nENCRYPTED', hw.encryptedData.length, hw)
  53. const decrypted = decrypt(hw)
  54. console.log('\nDECRYPTED', decrypted)
  55. console.log('\nJSON PARSED', JSON.parse(decrypted))
  56. },
  57. mounted: function () {
  58. //
  59. },
  60. }
  61. </script>