创建des.js文件
// 安装 !!npm install crypto-js --save
vue2版
// 安装 !!npm install crypto-js --save
import CryptoJS from "../node_modules/crypto-js/crypto-js.js";
const defaultKey = '你的密钥'
// DES加密
export const encryptDes = (message, key = defaultKey) => {
const keyHex = CryptoJS.enc.Utf8.parse(key);
const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
};
// DES解密
export const decryptDes = (ciphertext, key = defaultKey) => {
const keyHex = CryptoJS.enc.Utf8.parse(key);
// direct decrypt ciphertext
const decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(ciphertext),
},
keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}
);
return decrypted.toString(CryptoJS.enc.Utf8);
};
页面使用
import { encryptDes } from "@/config/des";
encryptDes(uni.getStorageSync("defaultCard").patientIdentityCard,"你得密钥")
工具
vue3版
import CryptoJS from 'crypto-js';
const defaultKey = '默认密钥';
// AES 加密
export const encryptedAes = (val: string, key1 = defaultKey) => {
const key = CryptoJS.enc.Utf8.parse(key1);
let encryptedStr = CryptoJS.AES.encrypt(val, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}).toString();
return encryptedStr;
};
// aes 解密
export function decrypt(val: string, key = defaultKey) {
const key1 = CryptoJS.enc.Utf8.parse(key);
const decrypt = CryptoJS.AES.decrypt(val, key1, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
export const useDecryByAes = function (val: string, key = defaultKey) {
const fValue = decrypt(val, key);
return JSON.parse(decodeURIComponent(fValue));
};
//DES加密
export const encryptDes = (message, key = defaultKey) => {
const keyHex = CryptoJS.enc.Utf8.parse(key);
const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
};
// DES解密
export const decryptDes = (ciphertext, key = defaultKey) => {
const keyHex = CryptoJS.enc.Utf8.parse(key);
const decrypted = CryptoJS.DES.decrypt(
{
ciphertext: CryptoJS.enc.Base64.parse(ciphertext),
} as any,
keyHex,
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}
);
return decrypted.toString(CryptoJS.enc.Utf8);
};
// base64 加密
export const encryptBase64 = (input: string) => {
const wordArray = CryptoJS.enc.Utf8.parse(input);
return CryptoJS.enc.Base64.stringify(wordArray);
};
export const decryptDesBase64 = (input: string) => {
const parsedWordArray = CryptoJS.enc.Base64.parse(input);
return parsedWordArray.toString(CryptoJS.enc.Utf8);
};
理解一下
DES(Data Encryption Standard)是对称的,也就是说它使用同一个密钥来加密和解密数据。
DES算法具体通过对明文进行一系列的排列和替换操作来将其加密。过程的关键就是从给定的初始密钥中得到16个子密钥的函数。要加密一组明文,每个子密钥按照顺序(1-16)以一系列的位操作施加于数据上,每个子密钥一次,一共重复16次。每一次迭代称之为一轮。要对密文进行解密可以采用同样的步骤,只是子密钥是按照逆向的顺序(16-1)对密文进行处理。