python3 + Vue 應用 AES 數據加密


python3 + Vue 應用 AES 數據加密

高級加密標准(AES,Advanced Encryption Standard)為最常見的對稱加密算法(微信小程序加密傳輸就是用這個加密算法的)。對稱加密算法也就是加密和解密用相同的密鑰,具有以下幾個特點:

1、最常用的對稱加密算法
2、密鑰建立時間短、靈敏性好、內存需求低
3、實際使用中,使用工作模式為CTR(最好用BC去實現),此工作模式需要引入IV參數(16位的字節數組)
4、密鑰長度128/192/256,其中192與256需要配置無政策限制權限文件(JDK6)
5、填充模式最常用的兩種PKCS5Padding和PKCS7Padding,其中后者只有BC獨有。
6、加密和解密用到的密鑰是相同的,這種加密方式加密速度非常快,適合經常發送數據的場合。

python (ECB)應用

安裝:

  • pip install pycryptodome
import base64
import json
import re

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad


class AesCrypt(object):
    """
    AES 加密組件
    """

    def __init__(self, user, is_json=True):

        # 這里的密鑰長度必須是 16 24 32
        key = 'suiyi_' + user.get('Auth')
        self.is_json = is_json
        self.encode_ = 'utf-8'
        self.key = self.add_32(key)
        print(self.key)
        self.aes = AES.new(self.key, AES.MODE_ECB)  # 創建一個aes對象

    def add_32(self, key):
        """
        key 補齊32位
        :param key:
        :return:
        """
        # 字符串 a 不要小於32位
        a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
        key += a
        key = key[0:32]
        return key.encode(self.encode_)

    def aes_encrypt(self, text):
        """
        加密 支持 json 需在實例中制動 is_json = True
        :param text:
        :return:
        """
        if self.is_json:
            text = json.dumps(text, ensure_ascii=False)
            '''
            # js 的 JSON.stringify() 轉換字符串后 沒有冒號以及逗號后的空格 前后端字符串不一致導致加密串不一致 
            json.dumps({"name": "guaiwan"}, ensure_ascii=False) -> {"name": "guaiwan", "gender": "nan"}
            JSON.stringify({"name": "guaiwan"})                 -> {"name":"guaiwan","gender":"nan"}
            '''
            text = text.replace(": ", ':').replace(", ", ',')
        text = pad(text.encode('utf-8'), AES.block_size, style='pkcs7')
        encrypt_text = self.aes.encrypt(text)
        encrypt_text = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', base64.encodebytes(
            encrypt_text).decode(self.encode_))
        return base64.encodebytes(encrypt_text).decode().strip()

    def aes_decrypt(self, text):
        """
        解密 支持 json 需在實例中制動 is_json = True
        :param text:
        :return:
        """
        text = base64.decodebytes(text.encode(self.encode_))
        decrypt_bytes = self.aes.decrypt(text)
        decrypt_text = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', decrypt_bytes.decode(
            self.encode_))
        if self.is_json:
            decrypt_text = json.loads(decrypt_text)
        return decrypt_text


if __name__ == '__main__':
    user = {'Auth': '0000_zhangziyi'}
    pr = AesCrypt(user, is_json=True)
    data = {"unit": 1, "theme": "cur", "look_detail": True, "zero_empty": True, "zero_hide": True, "data_type": "sum"}
    en_text = pr.aes_encrypt(data)
    print('密文:', en_text)
    pr2 = AesCrypt(user, is_json=True)
    print('明文:', pr2.aes_decrypt(en_text))

Vue (ECB)應用

安裝:

  • cnpm install crypto-js --save
import store from '@/store'
import CryptoJS from 'crypto-js/crypto-js'

function add_secret_key (userAuth) {
  let key = 'suiyi_' + userAuth
  if (key.length < 32) {
    let a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    key += a.slice(0, 32 - key.length)
  } else if (key.length > 32) {
    key = key.slice(0, 32)
  }
  console.log(key)
  return key

}

/**
 * 加密
 * @param wordimport { aes_encrypt, aes_decrypt } from '../../libs/crypto'

aes_encrypt(this.data)
aes_decrypt(this.AES_data)
 * @param userAuth代碼
 * @param is_json
 * @returns {string}
 */
export const aes_encrypt = (word, userAuth, is_json = true) => {
  if (is_json) {
    word = JSON.stringify(word)
  }
  var key = CryptoJS.enc.Utf8.parse(add_secret_key(userAuth)) //  s/iqSaaE0F3tsLgMCkCZjvqptKKzqD9/pMUnMkCwNjg= Set
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}
/**
 * 解密
 * @param word
 * @param userAuth
 * @param is_json
 * @returns {string}
 */
export const aes_decrypt = (word, userAuth, is_json = true) => {
  var key = CryptoJS.enc.Utf8.parse(add_secret_key(userAuth))//  s/iqSaaE0F3tsLgMCkCZjvqptKKzqD9/pMUnMkCwNjg= Set
  var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  let decrypt_text = CryptoJS.enc.Utf8.stringify(decrypt)
  if (is_json) {
    decrypt_text = JSON.parse(decrypt_text)
  }
  return decrypt_text
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM