鸿蒙实现 SM3 算法,api10开始支持
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer } from '@kit.ArkTS';
import util from "@ohos.util";
interface YXGMResp {
hex?: string | null;
base64?: string | null;
data?: Uint8Array | null;
}
/*
* 字符串 Base64 编码
* */
static strToBase64(aStr: string): string {
if (aStr.length == 0) {
return "";
}
let base64 = new util.Base64Helper();
let arr = new Uint8Array(buffer.from(aStr, 'utf-8').buffer);
let base64Str: string = base64.encodeToStringSync(arr);
return base64Str;
}
/*
* uint8Array Base64 编码
* */
static uint8ArrayToBase64(arr: Uint8Array): string {
if (arr.length == 0) {
return "";
}
let base64 = new util.Base64Helper();
let base64Str: string = base64.encodeToStringSync(arr);
return base64Str;
}
/*
* uint8Array 转 Hex 16进制字符串
* */
static uint8ArrayToHex(arr: Uint8Array): string {
if (arr.length == 0) {
return "";
}
let hex: string = "";
arr.forEach((value) => {
let hex2 = value.toString(16);
hex += (hex2.length < 2 ? ("0" + hex2) : hex2);
});
return hex;
}
/*
* SM3 摘要算法
* */
static async sm3(aStr: string): Promise<YXGMResp> {
if (aStr.length == 0) {
return new Promise<YXGMResp>(reslove => {
reslove({
hex: "",
base64: "",
data: new Uint8Array([])
});
});
}
let mdAlgName = "SM3";
let message = aStr;
let md = cryptoFramework.createMd(mdAlgName);
await md.update({ data: new Uint8Array(buffer.from(message, 'utf-8').buffer) });
let mdResult = await md.digest();
let base64Str: string = this.uint8ArrayToBase64(mdResult.data);
let hex: string = this.uint8ArrayToHex(mdResult.data);
return new Promise<YXGMResp>(reslove => {
reslove({
hex: hex,
base64: base64Str,
data: mdResult.data
});
});
}