它只是一种将二进制数据转换为可打印字符的编码方式,属于编码算法而非加密算法。
该篇文章并非讲述加密算法的各种使用,主要说明内容: 在cocosCreator 3.x中对于明文数据的保护。
crypto-es
crypto-es
是 npm提供的用于加密和解密的包。
它提供了各种加密算法和工具,包括对称加密、哈希函数、数字签名和公钥加密等。此外,它还支持生成随机数、密码学密钥管理等。
在cocosCreator中使用crypto-es
,需要npm进行下载。打开终端,进入项目目录,然后运行命令:
npm install crypto-es
需要了解更多NPM,可参考文档:NPM的使用介绍
下载成功后,crypto-es
会放到项目目录 ./node_modules中。
然后在脚本中直接引用即可。
import CryptoES from "crypto-es";
简单的示例:
const key = "encrypt";
const value = "Hello Encrypt";
console.log("加密前的数据:", value);
let value_1 = CryptoES.AES.encrypt(value, key).toString();
console.log("加密后的数据:", value_1);
let value_2 = CryptoES.AES.decrypt(value_1, key).toString(CryptoES.enc.Utf8);
console.log("解密后的数据:", value_2);
/\*
加密前的数据: Hello Encrypt
加密后的数据: U2FsdGVkX1/cqGU/G7xGVONeYS4R6sRjZYkMeAmUcdQ=
解密后的数据: Hello Encrypt
\*/
更多内容可参考: npm crypto-es
封装
在此感谢oops-framework开源框架的作者,对加密相关进行了封装。
主要文件实现在:EncryptUtil.ts
import CryptoES from "crypto-es";
export class EncryptUtil {
private static _key: string = "";
private static _iv: CryptoES.lib.WordArray = null;
// 初始化加密库
static initCrypto(key: string, iv: string) {
this._key = key;
this._iv = CryptoES.enc.Hex.parse(iv);
}
// MD5加密
static md5(msg: string) {
return CryptoES.MD5(msg).toString();
}
// AES加密
static aesEncrypt(msg: string, key?: string, iv?: string): string {
return CryptoES.AES.encrypt(
msg,
this._key,
{
iv: this._iv,
format: this.JsonFormatter
},
).toString();
}
// AES解密
static aesDecrypt(str: string, key?: string, iv?: string): string {
const decrypted = CryptoES.AES.decrypt(
str,
this._key,
{
iv: this._iv,
format: this.JsonFormatter
},
);
return decrypted.toString(CryptoES.enc.Utf8);
}
private static JsonFormatter = {
stringify: function (cipherParams: any) {
const jsonObj: any = { ct: cipherParams.ciphertext.toString(CryptoES.enc.Base64) };
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
return JSON.stringify(jsonObj);
},
parse: function (jsonStr: any) {
const jsonObj = JSON.parse(jsonStr);
const cipherParams = CryptoES.lib.CipherParams.create(
{ ciphertext: CryptoES.enc.Base64.parse(jsonObj.ct) },
);
if (jsonObj.iv) {
cipherParams.iv = CryptoES.enc.Hex.parse(jsonObj.iv)
}
if (jsonObj.s) {
cipherParams.salt = CryptoES.enc.Hex.parse(jsonObj.s)
}
return cipherParams;
},
};
![img](https://img-blog.csdnimg.cn/img_convert/f9659fccf9c9c7b96c3e8d45d088cdfd.png)
![img](https://img-blog.csdnimg.cn/img_convert/1c9006272840f923d6eeabdbf870789b.png)
![img](https://img-blog.csdnimg.cn/img_convert/0e7351702a7f760c5b7b88e1d4b16e0f.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
,涵盖了95%以上大数据知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**