一.封装
ps:不需要iv的去掉即可
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer, util } from '@kit.ArkTS';
export class DESUtil {
private key: cryptoFramework.SymKey;
private iv: cryptoFramework.IvParamsSpec;
private cipher: cryptoFramework.Cipher;
private decoder: cryptoFramework.Cipher;
private static instance: DESUtil;
private constructor(key: string,iv:string) {
this.key = this.genSymKeyByData(key);
this.iv = this.genIvParamsSpec(iv);
this.cipher = cryptoFramework.createCipher('3DES192|CBC|PKCS7');
this.decoder = cryptoFramework.createCipher('3DES192|CBC|PKCS7');
}
public static getInstance(key: string,iv:string): DESUtil {
if (!DESUtil.instance) {
DESUtil.instance = new DESUtil(key,iv)
}
return DESUtil.instance;
}
// 加密消息
public encryptMessageWithDESCBC(message: string): string {
if (message.length == 0) {
return "";
}
try {
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
this.cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, this.key,this.iv);
let encryptData = this.cipher.doFinalSync(plainText);
let base = new util.Base64Helper();
return base.encodeToStringSync(encryptData.data);
} catch (err) {
console.error('decrypt failed,' + err);
return "";
}
}
// 解密消息
public decryptMessageWithDESCBC(message: string | undefined): string {
if (message == undefined || message.length == 0) {
return "";
}
this.decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, this.key,this.iv);
let base = new util.Base64Helper();
let plainText: cryptoFramework.DataBlob = { data: base.decodeSync(message) };
try {
let decryptData = this.decoder.doFinalSync(plainText);
let textDecoder = util.TextDecoder.create('utf-8');
return textDecoder.decodeWithStream(decryptData.data);
} catch (err) {
console.error('decrypt failed,' + err);
return "";
}
}
private genSymKeyByData(key: string) {
key = key.substring(0, 8);
let keyData = new Uint8Array(24);
keyData.set(new util.TextEncoder().encodeInto(key))
let symKeyBlob: cryptoFramework.DataBlob = { data: keyData };
let symGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
let symKey = symGenerator.convertKeySync(symKeyBlob);
return symKey;
}
private genIvParamsSpec(iv: string): cryptoFramework.IvParamsSpec {
iv = iv.substring(0, 8);
let dataIv = new Uint8Array(24);
dataIv.set(new util.TextEncoder().encodeInto(iv))
let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
let ivParamsSpec: cryptoFramework.IvParamsSpec = {
algName: 'IvParamsSpec',
iv: ivBlob
};
return ivParamsSpec;
}
}
二.调用
// key
const res = DESUtil.getInstance('key')
// 加密
const encrypted = res.encryptMessageWithDESCBC( res.encryptMessageWithDESCBC('pas'))
// 解密
const decrypted = res.decryptMessageWithDESCBC(res.decryptMessageWithDESCBC(encrypted))