Implement DES encryption and decryption in Vue

1 Introduction

DES is a symmetric encryption (Data Encryption Standard) algorithm. It was officially licensed by the U.S. government in 1977 as a method of encrypting 64-bit data with a 56-bit key. The general password length is 8 bytes, of which 56-bit encryption key, and each 8th bit is used as a parity check.
The DES algorithm generally has two key points, the first is the encryption algorithm, and the second is the data complement. Common encryption algorithms include ECB mode and CBC mode.

ECB mode: ECB (electronic cipher book) is actually very simple. It is to encrypt or decrypt data according to a segment of 8 bytes by DES to obtain a segment of 8 bytes of ciphertext or plaintext, and the last segment is less than 8 bytes ( Generally add 0 or F), make up 8 bytes according to the demand for calculation (parallel calculation), and then connect the calculated data together in order, and each piece of data does not affect each other.

Advantages: simple, conducive to parallel computing, errors will not be transmitted;
disadvantages: cannot hide the pattern of the plaintext, and may actively attack the plaintext;

CBC mode: ciphertext grouping link mode, it is more troublesome, the encryption steps are as follows:

  1. First, group the data into groups of 8 bytes to get D1D2...Dn (if the data is not an integer multiple of 8, it involves data bit supplementation);
  2. The result of the XOR of the first set of data D1 and vector I is DES encrypted to obtain the first set of ciphertext C1 (note: there is a vector I here, and the vector I is not used in ECB mode);
  3. The result after the exclusive OR of the second set of data D2 and the encryption result C1 of the first set is DES encrypted to obtain the second set of ciphertext C2;
  4. The subsequent data and so on, get Cn
  5. Connected as C1C2C3...Cn in order is the encryption result;

Advantages: It is not easy to attack actively, and the security is better than ECB, which is the standard of SSL and IPSec;
Disadvantages: it is not conducive to parallel computing, error transmission, and requires initialization vector IV;

2. Implement DES encryption and decryption in Vue

Install crypto-js
crypto-js npm address

npm install crypto-js

2.1 ECB mode

2.1.1 Packaging method

// utils/des.js

import cryptoJs from 'crypto-js';

// 随机生成指定数量的16进制key(该方法非必须,也可自己指定key)
const generatekey = (num) => {
    
    
  let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let key = "";
  for (var i = 0; i < num; i++) {
    
    
    let randomPoz = Math.floor(Math.random() * library.length);
    key += library.substring(randomPoz, randomPoz + 1);
  }
  return key;
}
/*
* message:需要解密的字符串,
* key: 密钥(加密解密密钥同一个)
*/
//DES加密
const encryptDes = (message, key = 'abcd@1234') => {
    
    
  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(); // 返回hex格式密文,如需返回base64格式:encrypted.toString()
}


//DES解密
const decryptDes = (message, key = 'abcd@1234') => {
    
    
  var keyHex = cryptoJs.enc.Utf8.parse(key)
  var decrypted = cryptoJs.DES.decrypt(
    {
    
    
      ciphertext: cryptoJs.enc.Hex.parse(message)
    }, // 若 message 是 base64 格式,则无需转16进制hex,直接传入 message 即可
    keyHex,
    {
    
    
      mode: cryptoJs.mode.ECB,
      padding: cryptoJs.pad.Pkcs7
    }
  )
  return decrypted.toString(cryptoJs.enc.Utf8)
}

export {
    
    
  generatekey,
  encryptDes,
  decryptDes,
}

2.1.2 Introduction and use

<script>
import {
    
     encryptDes, decryptDes,generatekey } from '@/utils/des.js'

export default {
    
    
  data() {
    
    
    return {
    
    
      info:{
    
    
        userName:'test',
        passWord:'Hi@123'
      }
    };
  },
  methods: {
    
    
    test(){
    
    
      const key = generatekey(8); // 也可直接指定key let key = 'des';
      
      //如果是对象/数组的话,需要先JSON.stringify转换成字符串
      const encrypts = encryptDes(JSON.stringify(this.info), key);
      const dess = JSON.parse(decryptDes(encrypts, key));

      console.log(encrypts, dess)
    }
  },
  mounted() {
    
    
    this.test();
  },
};
</script>

2.2 CBC mode

2.2.1 Encapsulation method

// utils/des.js

import cryptoJs from 'crypto-js';


// 随机生成指定数量的16进制key(该方法非必须,也可直接指定固定key值)
const generatekey = (num) => {
    
    
  let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let key = "";
  for (var i = 0; i < num; i++) {
    
    
    let randomPoz = Math.floor(Math.random() * library.length);
    key += library.substring(randomPoz, randomPoz + 1);
  }
  return key;
}

/*
* message: 需要加解密的文本
  key: 加解密的秘钥
  iv: 偏移量,最短8位数,ecb模式不需要此参数
*/

// 加密
const encrypt =  (message, key = 'abcd@1234', iv = 'hello world') => {
    
    
  const keyHex = cryptoJs.enc.Utf8.parse(key); // 秘钥
  const ivHex = cryptoJs.enc.Utf8.parse(iv); // 偏移量
  const option = {
    
     iv: ivHex, mode: cryptoJs.mode.CBC, padding: cryptoJs.pad.Pkcs7 }; // Pkcs7填充方式
  const encrypted = cryptoJs.DES.encrypt(message, keyHex, option);
  return encrypted.ciphertext.toString() //  加密出来为 hex格式密文
}

// 解密
const decrypt = (message, key = 'abcd@1234', iv = 'hello world') => {
    
    
  const keyHex = cryptoJs.enc.Utf8.parse(key)
  const ivHex = cryptoJs.enc.Utf8.parse(iv)
  const 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)
}

export {
    
    
  generatekey,
  encrypt,
  decrypt,
}

2.2.2 Introduction and use

<script>
import {
    
     encrypt, decrypt, generatekey } from '@/utils/des.js'

export default {
    
    
  data() {
    
    
    return {
    
    
      info:{
    
    
        userName:'test',
        passWord:'Hi@123'
      }
    };
  },
  methods: {
    
    
    test(){
    
    
      const key = generatekey(8); // 也可直接指定固定key值 let key = 'des';
      
      //如果是对象/数组的话,需要先JSON.stringify转换成字符串
      const encrypts = encrypt(JSON.stringify(this.info), key, '12345678');
      const dess = JSON.parse(decrypt(encrypts, key, '12345678'));

      console.log(encrypts, dess)
    }
  },
  mounted() {
    
    
    this.test();
  },
};
</script>

Guess you like

Origin blog.csdn.net/ZYS10000/article/details/114762338