鸿蒙-MD5摘要(ArkTS)

SDK 版本:HarmonyOS NEXT Developer Beta2 SDK (5.0.0.31)
DevEco-Studio 版本:DevEco Studio NEXT Developer Beta2 (5.0.3.502)
工程机版本:ALN-AL00 NEXT.0.0.31

简介

MD5 算法常常被用来验证网络文件传输的完整性,防止文件被人篡改。MD5 全称是报文摘要算法(Message-Digest Algorithm 5),此算法对任意长度的信息逐位进行计算,产生一个二进制长度为 128 位(十六进制长度就是 32 位)的“指纹”(或称“报文摘要”),不同的文件产生相同的报文摘要的可能性是非常非常之小的。

Linux 下 md5sum 用法 (查看文件或字符串的 md5 值)

md5sum 命令采用 MD5 报文摘要算法(128 位)计算和检查文件的校验和。一般来说,安装了 Linux 后,就会有 md5sum 这个工具,直接在命令行终端直接运行。

windows 下如果安装了 git-bash 也可以在所在的文件夹下,右击,选择[Git Bash Here],也可以直接使用 md5sum 命令。

MD5 ArkTS 实现代码

MD5Util.ets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* Copyright (c) 2024. Dench.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { cryptoFramework } from "@kit.CryptoArchitectureKit";
import { buffer } from "@kit.ArkTS";
import { hash } from "@kit.CoreFileKit";
import { systemDateTime } from "@kit.BasicServicesKit";

/**
* 计算字符串Md5
*/
export async function md5(messageText: string): Promise<string> {
const md = cryptoFramework.createMd("MD5");
await md.update({
data: new Uint8Array(buffer.from(messageText, "utf-8").buffer),
});
const mdOutput = await md.digest();
console.info("md mdOutput: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("md mdLen: " + mdLen);
const result = buffer.from(mdOutput.data.buffer).toString("hex");
console.info("md result: " + result);
return result;
}

// 文件Md5, 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256", 此处使用"md5"
export async function fileMd5(filePath: string): Promise<string> {
try {
const t = systemDateTime.getTime();
const result = await hash.hash(filePath, "md5");
console.info("fileMd5: result=" + result);
console.info(`fileMd5: duration=${systemDateTime.getTime() - t}`);
return result;
} catch (err) {
console.error(`fileMd5: ${JSON.stringify(err)}`);
return "";
}
}

// 文件MD5,大文件读写效率低,有性能瓶颈,采用上面的文件Hash算法
// export async function fileMd5(path: string, algName: string = "MD5"): Promise<string> {
// console.info("fileMd5: path=" + path)
// let md = cryptoFramework.createMd(algName);
// try {
// const t = systemDateTime.getTime();
// let file = await fs.open(path, fs.OpenMode.READ_ONLY);
// let arrayBuffer = new ArrayBuffer(4096);
// let offset = 0;
// let readOptions: ReadOptions = {
// offset: offset,
// length: 4096
// };
// let len = await fs.read(file.fd, arrayBuffer, readOptions);
// while (len > 0) {
// // console.info("md read file len: " + len);
// const bf = buffer.from(arrayBuffer).subarray(0, len);
// // console.info("md bf: " + bf.buffer.byteLength);
// const uint8 = new Uint8Array(bf.buffer);
// // console.info("md uint8: " + uint8.byteLength);
// await md.update({ data: uint8 });
// offset += len;
// readOptions.offset = offset;
// len = await fs.read(file.fd, arrayBuffer, readOptions);
// }
// try {
// fs.close(file);
// } catch (e) {
// console.info(JSON.stringify(e));
// }
// let mdOutput = await md.digest();
// // console.info("md mdOutput: " + mdOutput.data);
// let mdLen = md.getMdLength();
// // console.info("md mdLen: " + mdLen);
// const result = buffer.from(mdOutput.data.buffer).toString('hex');
// console.info("md succeed: " + result);
// console.info(`md duration=${systemDateTime.getTime() - t}`);
// return result;
// } catch (e) {
// console.error("md error: " + JSON.stringify(e));
// return ''
// }
// }

Reference

https://www.cnblogs.com/kevingrace/p/10201723.html
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-hash-V5

作者

Dench

发布于

2024-06-27

更新于

2024-06-27

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×