1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| 先在oh-package.json5中引用库 "@ohos/crypto-js": "2.0.5"
在创建工具类,供外部调用
// CryptoUtils.ts import { CryptoJS } from '@ohos/crypto-js';
export class DesEncryptorJS {
/** * DES 加密(ECB + PKCS7) * @param data 明文 * @param keyStr 密钥(会自动补齐 8 位) * @returns Base64 加密结果 */ static desEncrypt(data: string, keyStr: string): string { // DES key 必须 8 字节 let key = keyStr.padEnd(8, '0'); let parsedKey = CryptoJS.enc.Utf8.parse(key);
let encrypted = CryptoJS.DES.encrypt(data, parsedKey, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, });
return encrypted.toString(); }
/** * DES 解密(ECB + PKCS7) * @param encryptedData Base64 密文 * @param keyStr 密钥 * @returns 明文 */ static desDecrypt(encryptedData: string, keyStr: string): string { let key = keyStr.padEnd(8, '0'); let parsedKey = CryptoJS.enc.Utf8.parse(key);
let decrypted = CryptoJS.DES.decrypt(encryptedData, parsedKey, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, });
return decrypted.toString(CryptoJS.enc.Utf8); }
/** * AES 加密(默认 ECB + PKCS7) * @param data 明文 * @param keyStr 密钥(16/24/32 字节) * @returns Base64 密文 */ static aesEncrypt(data: string, keyStr: string): string { let key = CryptoJS.enc.Utf8.parse(keyStr); let encrypted = CryptoJS.AES.encrypt(data, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, });
return encrypted.toString(); }
/** * AES 解密 * @param encryptedData Base64 密文 * @param keyStr 密钥 * @returns 明文 */ static aesDecrypt(encryptedData: string, keyStr: string): string { let key = CryptoJS.enc.Utf8.parse(keyStr); let decrypted = CryptoJS.AES.decrypt(encryptedData, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, });
return decrypted.toString(CryptoJS.enc.Utf8); }
/** * MD5 加密 * @param data 明文 * @returns MD5 十六进制字符串 */ static md5(data: string): string { return CryptoJS.MD5(data).toString(CryptoJS.enc.Hex); } }
|