function doMdByPromise() {
// 摘要算法名称。
let mdAlgName = "MD5";
// 要进行摘要的数据。
let message = "Hello,中国";
let md = cryptoFramework.createMd(mdAlgName);
console.info("[Promise]: Md algName is: " + md.algName);
// 如果数据量较小,可以使用 update() 一次传入所有数据。输入参数的长度没有限制。
let promiseMdUpdate = md.update({ data: stringToUint8Array(message) });
promiseMdUpdate.then(() => {
// 调用 digest() 以返回结果。
let PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(digestOutput => {
let mdOutput = digestOutput.data;
let str2 = uint8ArrayToHexStr(mdOutput);
let str = base64.encodeToStringSync(mdOutput);
let str1 = uint8ArrayToString1(mdOutput);
console.info("[Promise]: MD result: " + mdOutput);
let mdLen = md.getMdLength();
console.info("[Promise]: MD len: " + mdLen);
}).catch((error: BusinessError) => {
console.error("[Promise]: error: " + error.message);
});
}
公共方法:
//摘要结果是Uint8Array类型,转换得到十六进制字符串数据
function uint8ArrayToHexStr(data: Uint8Array): string {
let hexString = "";
let i: number;
for (i = 0; i < data.length; i++) {
let char = ('00' + data[i].toString(16)).slice(-2);
hexString += char;
}
return hexString;
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array:Uint8Array) {
// 将UTF-8编码转换成Unicode编码
let out: string = "";
let index: number = 0;
let len: number = array.length;
while (index < len) {
let character = array[index++];
switch(character >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
out += String.fromCharCode(character);
break;
case 12:
case 13:
out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F));
break;
case 14:
out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) | ((array[index++] & 0x3F) << 0));
break;
default:
break;
}
}
return out;
}
MD5加密参考一下demo:
公共方法: