Vue implements CBC encryption/decryption

We now introduce input into the terminal

npm install crypto-js

After introducing dependencies, I suddenly discovered that crypto-js is indeed an encryption artifact.
Then let’s write it directly in the App.vue component like this

<template>
  <div>
    <input v-model="plainText" placeholder="输入明文" />
    <button @click="encrypt">加密</button>
    <button @click="decrypt">解密</button>
    <p>密文: {
    
    {
    
     cipherText }}</p>
    <p>解密后的明文: {
    
    {
    
     decryptedText }}</p>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      plainText: '',
      cipherText: '',
      decryptedText: '',
      key: '0123456789abcdef', // 密钥
      iv: 'abcdef0123456789' // 初始向量
    };
  },
  methods: {
    
    
    encrypt() {
    
    
      // CBC加密
      const cipher = this.$CryptoJS.AES.encrypt(this.plainText, this.$CryptoJS.enc.Hex.parse(this.key), {
    
    
        iv: this.$CryptoJS.enc.Hex.parse(this.iv)
      }).ciphertext;
      this.cipherText = this.$CryptoJS.enc.Hex.stringify(cipher);
    },
    decrypt() {
    
    
      // CBC解密
      const cipher = this.$CryptoJS.enc.Hex.parse(this.cipherText);
      const decrypted = this.$CryptoJS.AES.decrypt({
    
     ciphertext: cipher }, this.$CryptoJS.enc.Hex.parse(this.key), {
    
    
        iv: this.$CryptoJS.enc.Hex.parse(this.iv)
      });
      this.decryptedText = decrypted.toString(this.$CryptoJS.enc.Utf8);
    }
  },
  mounted() {
    
    
    // 在Vue实例中引入CryptoJS库
    this.$CryptoJS = require('crypto-js');
  }
};
</script>

Here I did not use npm to import directly but used require to directly assign the crypto-js object to $CryptoJS on the prototype chain. This makes it easier to use the
overall
plainText in the data. It is the user input corresponding to the content we want to encrypt.
After the encryption is completed, it will Assign the value to cipherText
and finally decrypt it through cipherText. Then the content is assigned to decryptedText.
The key secret key and iv initialization vector must be communicated clearly with your own backend or other people because this is an encryption rule. If the person who owns your data follows your rules Different prompts indicate that decryption cannot be obtained.
The encryption and decryption methods are all officially provided by crypto-js. You
can take a look and just copy and change it for use.
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/133342736