aes加密解密算法

React中aes加密解密算法簡單使用

​ 本文使用aes加密算法完成解密加密,在加密中使用CBCmode,PKcs7padding,IV_STRINGiv等,在操作中需要第一步先把對應的字符串轉化爲utf8格式,key值使用默認key值的前16位utf8格式的字符串,然後使用encrypt方法進行加密,完成加密後將加密數據轉化成Base64字符串格式,解密方法和加密方法類似只是反向操作。

import CryptoJS from 'crypto-js'

const IV_STRING = CryptoJS.enc.Utf8.parse('ShaosongApping')
export function SYEncryptString(message, key) {
  // 將加密字符串轉化爲utf8類型
  message = CryptoJS.enc.Utf8.parse(message)
  // key 值進行截取
  key = CryptoJS.enc.Utf8.parse(String(key).substr(0, 16))
  // 使用加密encrypt進行加密
  const cipher = CryptoJS.AES.encrypt(message, key, {
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
    iv: IV_STRING,
  })
  // 將加密後的數據轉換成 Base64
  const base64Cipher = cipher.ciphertext.toString(CryptoJS.enc.Base64)
  return base64Cipher
}

export function SYDecryptString(encrypted, key) {
  try {
    key = CryptoJS.enc.Utf8.parse(String(key).substr(0, 16))
    // 將加密密文先通過base64解碼字符串
    let decData = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Base64.parse(encrypted))
    // 使用加密decrypt進行加密
    const decipher = CryptoJS.AES.decrypt(decData, key, {
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
      iv: IV_STRING,
    })

    // 將解密對象轉換成 UTF8 的字符串
    const resultDecipher = decipher.toString(CryptoJS.enc.Utf8)
    return resultDecipher
  } catch (err) {
    return encrypted
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章