废话不多说,本章节我们实现鸿蒙两种MD5加密实现方法。
一、使用鸿蒙系统库
import cryptoFramework from '@ohos.security.cryptoFramework';
import buffer from '@ohos.buffer';
async function doMd() {
let mdAlgName = "MD5"; // Algorithm to use.
let message = "123456"; // Message to be digested.
let md = cryptoFramework.createMd(mdAlgName);
// If the data to be processed is short, use update() to pass in the full data at a time. The data to be passed in by a single **update()** operation is not size bound.
await md.update({ data: new Uint8Array(buffer.from(message, 'utf-8').buffer) });
let mdResult = await md.digest();
let md5str = Array.from(mdResult.data).map(byte => byte.toString(16).padStart(2, '0')).join('');
console.info('Md result:' + md5str );
let mdLen = md.getMdLength();
console.info("md len: " + mdLen);
}
按照官方文档只给出了
let mdResult = await md.digest();
执行完获取到的是加密后的Uint8Array类型,如果输出字符串则调用如下方法:
let md5str = Array.from(mdResult.data).map(byte => byte.toString(16).padStart(2, '0')).join('');</pre>
二、使用鸿蒙三方库
首先在oh-package.json5加入三方依赖:
"dependencies": {
"@ohos/crypto-js":"2.0.2"
}
然后在代码中导入三方库:
import CryptoJS from '@ohos/crypto-js'
在需要MD5加密的地方直接调用:
let md5str: string = CryptoJS.MD5('123456').toString();
网友评论