base64 Encoder via crypto-js

只愿长相守 提交于 2019-12-08 03:22:35

问题


I want to Encode number to character.

  • How Can I encode to base64 in output?

Code:

const CryptoJS = require('crypto-js');

function msg() {
  return '7543275'; // I want to encrypt this number to character
}

const msgLocal = msg();

// Encrypt
const ciphertext = CryptoJS.AES.encrypt(msgLocal, 'password');

// Decrypt
const bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'password');
const plaintext = bytes.toString(CryptoJS.enc.Utf8);

console.log(plaintext);

回答1:


Solved.

const CryptoJS = require('crypto-js');

// OUTPUT
console.log(encrypt()); // 'NzUzMjI1NDE='
console.log(decrypt()); // '75322541'

function encrypt() {
  // INIT
  const myString = '75322541'; // Utf8-encoded string

  // PROCESS
  const encryptedWord = CryptoJS.enc.Utf8.parse(myString); // encryptedWord Array object
  const encrypted = CryptoJS.enc.Base64.stringify(encryptedWord); // string: 'NzUzMjI1NDE='
  return encrypted;
}

function decrypt() {
  // INIT
  const encrypted = 'NzUzMjI1NDE='; // Base64 encrypted string

  // PROCESS
  const encryptedWord = CryptoJS.enc.Base64.parse(encrypted); // encryptedWord via Base64.parse()
  const decrypted = CryptoJS.enc.Utf8.stringify(encryptedWord); // decrypted encryptedWord via Utf8.stringify() '75322541'
  return decrypted;
}


来源:https://stackoverflow.com/questions/48524452/base64-encoder-via-crypto-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!