Skip to content

LimeCrypto 加密

UTS版cryptoJs,暂时支持MD5、SHA1、SHA256、 SHA512、AES,兼容uniapp/uniappx

功能概述

本模块提供以下加密功能:

  • 哈希算法(MD5/SHA1/SHA256/SHA512)
  • HMAC-SHA256 签名
  • AES 对称加密(支持多种模式和填充方案)
  • 多种编码格式转换(UTF8/Hex/Base64等)

文档

crypto

安装

插件市场入口 导入,非源码APP需要自定义基座。

使用

js
import { useCrypto } from '@/uni_modules/lime-crypto'
const crypto = useCrypto()

哈希算法

js
const message = "hello world";
const hash = crypto.MD5(message);
console.log("MD5结果:", hash.toString()); // 转16进制
console.log("MD5结果:", crypto.enc.Hex.stringify(hash)); // 转16进制

SHA系列

js
const sha1Hash = crypto.SHA1(message);
const sha256Hash = crypto.SHA256(message);
const sha512Hash = crypto.SHA512(message);

// 转Base64
console.log("sha1Hash:", crypto.enc.Base64.stringify(sha1Hash));
console.log("sha256Hash:", crypto.enc.Base64.stringify(sha256Hash));
console.log("sha512Hash:", crypto.enc.Base64.stringify(sha512Hash));

HMAC-SHA256

js
const secret = "mySecretKey";
const hmacHash = crypto.HmacSHA256(message, secret);
console.log("HMAC:", crypto.enc.Hex.stringify(hmacHash));

AES 加密/解密

加密

js
const plaintext = "敏感数据123";
const key = "16/24/32字节密钥"; // 根据AES类型选择长度

// 基础加密 (使用默认ECB模式+PKCS7填充)
const encrypted = crypto.AES.encrypt(plaintext, key);
console.log("加密结果(Hex):", crypto.enc.Hex.stringify(encrypted));

const encryptedCBC = crypto.AES.encrypt(
	plaintext, 
	crypto.enc.Utf8.parse(key), // 支持WordArray类型密钥
	{
		iv: crypto.enc.Utf8.parse("1234567890abcdef"),
		mode: crypto.mode.CBC,
		padding: crypto.pad.Pkcs7 
	}
);

解密

js
const ciphertextHex = "加密后的16进制字符串";
const ciphertext = crypto.enc.Hex.parse(ciphertextHex);

// 简单解密
const decrypted = crypto.AES.decrypt(ciphertext, key);
console.log("解密结果:", decrypted.toString(crypto.enc.Utf8));

// 带配置解密
const decryptedCBC = crypto.AES.decrypt(
	ciphertext,
	key,
	// 需使用加密时的相同配置
	{
		iv: crypto.enc.Utf8.parse("1234567890abcdef"),
		mode: crypto.mode.CBC,
		padding: crypto.pad.Pkcs7 
	} 
);

AES 加密模式

模式名称描述注意事项
CBC密码块链模式,每个块依赖前一个块- 必须提供16字节IV
- IV需唯一且随机
CFB将块密码转为流密码,支持逐字节加密- IV需随机且不可预测
- 错误传播影响后续数据
CTR计数器模式,支持并行计算- 计数器必须永不重复
- 需管理好nonce
CTRGladman优化的CTR模式实现- 非标准实现
- 可能与其他库不兼容
ECB简单块加密,相同明文生成相同密文- 不推荐正式使用
- 存在安全漏洞
OFB输出反馈模式,错误不传播- 需要完整IV
- 加密解密需严格同步

填充方式

填充名称描述注意事项
Pkcs7填充字节值为填充长度(如缺3字节则填0x03)- 最通用方案
- 数据长度需为块大小整数倍
AnsiX923末尾为填充长度,中间填0- 部分旧系统不支持
Iso10126末尾为填充长度,中间填随机值- 已过时标准
- 慎用
Iso97971使用比特填充方案- 特殊位流场景专用
- 与其他库不兼容
NoPadding无填充,APP端字符必须为16的整倍数- 数据长度必须严格匹配块大小
ZeroPadding用0x00填充至块大小- 无法区分数据结尾和填充
- 可能跨平台不兼容

编码器 (ENC)

js
// 字符串与WordArray互转
const wordArray = crypto.enc.Utf8.parse("需要加密的内容"); // UTF8转二进制
const base64Str = crypto.enc.Base64.stringify(wordArray); // 转Base64

// 支持编码类型
crypto.enc.Hex        // 16进制
crypto.enc.Base64     // 标准Base64
crypto.enc.Base64url  // URL安全Base64
crypto.enc.Latin1     // Latin1编码

源代码

组件源码