vue DES 加密

  1. 安装crypto-js

cnpm install crypto-js --save

  1. 封装一个des.js

ECB模式

import cryptoJs from 'crypto-js'

// DES加密
export const encryptDes = (message, key) => {
  var keyHex = cryptoJs.enc.Utf8.parse(key)
  var option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 }
  var encrypted = cryptoJs.DES.encrypt(message, keyHex, option)
  return encrypted.ciphertext.toString()
}

// DES解密
export const decryptDes = (message, key) => {
  var keyHex = cryptoJs.enc.Utf8.parse(key)
  var decrypted = cryptoJs.DES.decrypt(
    {
      ciphertext: cryptoJs.enc.Hex.parse(message)
    },
    keyHex,
    {
      mode: cryptoJs.mode.ECB,
      padding: cryptoJs.pad.Pkcs7
    }
  )
  return decrypted.toString(cryptoJs.enc.Utf8)
}

CBC模式

import cryptoJs from 'crypto-js'

// DES加密
export const encryptDes = (message, key, iv) => {
  var keyHex = cryptoJs.enc.Utf8.parse(key)
  var ivHex = cryptoJs.enc.Utf8.parse(iv)
  var option = { iv: ivHex, mode: cryptoJs.mode.CBC, padding: cryptoJs.pad.Pkcs7 }
  var encrypted = cryptoJs.DES.encrypt(message, keyHex, option)
  return encrypted.ciphertext.toString()
}

// DES解密
export const decryptDes = (message, key, iv) => {
  var keyHex = cryptoJs.enc.Utf8.parse(key)
  var ivHex = cryptoJs.enc.Utf8.parse(iv)
  var decrypted = cryptoJs.DES.decrypt(
    {
      ciphertext: cryptoJs.enc.Hex.parse(message)
    },
    keyHex,
    {
      iv: ivHex,
      mode: cryptoJs.mode.CBC,
      padding: cryptoJs.pad.Pkcs7
    }
  )
  return decrypted.toString(cryptoJs.enc.Utf8)
}

  1. 使用des.js

ECB模式

import { encryptDes, decryptDes } from './des.js'  // 引用路径根据自己的文件结构而定

encryptDes('要加密的数据', '加密的key')
decryptDes('要解密的数据', '解密的key')

CBC模式

import { encryptDes, decryptDes } from './des.js'  // 引用路径根据自己的文件结构而定

encryptDes('要加密的数据', '加密的key', '加密的iv')
decryptDes('要解密的数据', '解密的key', '解密的iv')

posted @ 2019-01-29 12:01  shifeng~  阅读(4570)  评论(0编辑  收藏  举报