中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
微信扫码分享
import cryptoFramework from '@ohos.security.cryptoFramework'; import { BusinessError } from '@ohos.base'; import util from '@ohos.util'; import buffer from '@ohos.buffer'; function stringToUint8Array(str: string) { return new Uint8Array(buffer.from(str, 'utf-8').buffer); } function hexStrTouint8Array(data: string): Uint8Array { return new Uint8Array(buffer.from(data, 'hex').buffer); ; } let base64 = new util.Base64Helper(); // 以Promise方式完成摘要 function doMdByPromise() { // 摘要算法名称。 let mdAlgName = "SM3"; // 要进行摘要的数据。 let message = "c5083fb7bac6a209947c09c04bdff3a3dbd68d9bf2bf3e788ef085cf752525d9e2f145f875f687d88d189c0f6ed4739cf81fafa689c7e7153a000376741a25f18992b6ff6b8e2d10"; let md = cryptoFramework.createMd(mdAlgName); console.info("[Promise]: Md algName is: " + md.algName); let promiseMdUpdate = md.update({ data: hexStrTouint8Array(message) }); promiseMdUpdate.then(() => { // 调用 digest() 以返回结果。 let PromiseMdDigest = md.digest(); return PromiseMdDigest; }).then(digestOutput => { let mdOutput = digestOutput.data; let str2 = base64.encodeToStringSync(mdOutput); let str = uint8ArrayToHexStr(mdOutput) console.info("[Promise]: MD result: " + str); let mdLen = md.getMdLength(); console.info("[Promise]: MD len: " + mdLen); }).catch((error: BusinessError) => { console.error("[Promise]: error: " + error.message); }); } 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; } @Entry @Component struct Page240603210944057 { @State message: string = 'Hello World'; build() { Row() { Column() { Button('do sm3').onClick(() => { doMdByPromise(); }) } .width('100%') } .height('100%') } }