1# @ohos.file.hash (文件哈希处理)
2
3该模块提供文件哈希处理能力,对文件内容进行哈希处理。
4
5> **说明:**
6>
7> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8
9## 导入模块
10
11```ts
12import { hash } from '@kit.CoreFileKit';
13```
14
15## 使用说明
16
17使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考:
18
19  ```ts
20  import { UIAbility } from '@kit.AbilityKit';
21  import { window } from '@kit.ArkUI';
22
23  export default class EntryAbility extends UIAbility {
24    onWindowStageCreate(windowStage: window.WindowStage) {
25      let context = this.context;
26      let pathDir = context.filesDir;
27    }
28  }
29  ```
30
31使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考:[应用上下文Context-获取应用文件路径](../../application-models/application-context-stage.md#获取应用文件路径)
32
33## hash.hash
34
35hash(path: string, algorithm: string): Promise<string>
36
37计算文件的哈希值,使用Promise异步回调。
38
39**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
40
41**系统能力**:SystemCapability.FileManagement.File.FileIO
42
43**参数:**
44
45| 参数名    | 类型   | 必填 | 说明                                                         |
46| --------- | ------ | ---- | ------------------------------------------------------------ |
47| path      | string | 是   | 待计算哈希值文件的应用沙箱路径。                             |
48| algorithm | string | 是   | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 |
49
50**返回值:**
51
52  | 类型                    | 说明                         |
53  | --------------------- | -------------------------- |
54  | Promise<string> | Promise对象。返回文件的哈希值。表示为十六进制数字串,所有字母均大写。 |
55
56**错误码:**
57
58以下错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
59
60| 错误码ID | 错误信息 |
61| -------- | -------- |
62| 13900020 | Invalid argument |
63| 13900042 | Unknown error |
64
65**示例:**
66
67  ```ts
68  import { BusinessError } from '@kit.BasicServicesKit';
69  let filePath = pathDir + "/test.txt";
70  hash.hash(filePath, "sha256").then((str: string) => {
71    console.info("calculate file hash succeed:" + str);
72  }).catch((err: BusinessError) => {
73    console.error("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
74  });
75  ```
76
77## hash.hash
78
79hash(path: string, algorithm: string, callback: AsyncCallback<string>): void
80
81计算文件的哈希值,使用callback异步回调。
82
83**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
84
85**系统能力**:SystemCapability.FileManagement.File.FileIO
86
87**参数:**
88
89| 参数名    | 类型                        | 必填 | 说明                                                         |
90| --------- | --------------------------- | ---- | ------------------------------------------------------------ |
91| path      | string                      | 是   | 待计算哈希值文件的应用沙箱路径。                             |
92| algorithm | string                      | 是   | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 |
93| callback  | AsyncCallback<string> | 是   | 异步计算文件哈希操作之后的回调函数(其中给定文件哈希值表示为十六进制数字串,所有字母均大写)。 |
94
95**错误码:**
96
97以下错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
98
99| 错误码ID | 错误信息 |
100| -------- | -------- |
101| 13900020 | Invalid argument |
102| 13900042 | Unknown error |
103
104**示例:**
105
106  ```ts
107  import { BusinessError } from '@kit.BasicServicesKit';
108  let filePath = pathDir + "/test.txt";
109  hash.hash(filePath, "sha256", (err: BusinessError, str: string) => {
110    if (err) {
111      console.error("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
112    } else {
113      console.info("calculate file hash succeed:" + str);
114    }
115  });
116  ```
117## hash.createHash<sup>12+</sup>
118
119createHash(algorithm: string): HashStream;
120
121创建并返回 HashStream 对象,该对象可用于使用给定的 algorithm 生成哈希摘要。
122
123**系统能力**:SystemCapability.FileManagement.File.FileIO
124
125**参数:**
126
127| 参数名 | 类型   | 必填 | 说明                                                         |
128| ------ | ------ | ---- | ------------------------------------------------------------ |
129| algorithm | string | 是  | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 |
130
131**返回值:**
132
133  | 类型            | 说明         |
134  | ------------- | ---------- |
135  | [HashStream](#hashstream12) | HashStream 类的实例 |
136
137**错误码:**
138
139接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
140
141**示例:**
142
143  ```ts
144  // pages/xxx.ets
145  import { fileIo as fs } from '@kit.CoreFileKit';
146
147  function hashFileWithStream() {
148    const filePath = pathDir + "/test.txt";
149    // 创建文件可读流
150    const rs = fs.createReadStream(filePath);
151    // 创建哈希流
152    const hs = hash.createHash('sha256');
153    rs.on('data', (emitData) => {
154      const data = emitData?.data;
155      hs.update(new Uint8Array(data?.split('').map((x: string) => x.charCodeAt(0))).buffer);
156    });
157    rs.on('close', async () => {
158      const hashResult = hs.digest();
159      const fileHash = await hash.hash(filePath, 'sha256');
160      console.info(`hashResult: ${hashResult}, fileHash: ${fileHash}`);
161    });
162  }
163  ```
164
165
166## HashStream<sup>12+</sup>
167
168HashStream 类是用于创建数据的哈希摘要的实用工具。由 [createHash](#hashcreatehash12) 接口获得。
169
170### update<sup>12+</sup>
171
172update(data: ArrayBuffer): void
173
174使用给定的 data 更新哈希内容,可多次调用。
175
176**系统能力**:SystemCapability.FileManagement.File.FileIO
177
178**错误码:**
179
180接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
181
182**示例:**
183
184  ```ts
185  // 创建哈希流
186  const hs = hash.createHash('sha256');
187  hs.update(new Uint8Array('1234567890'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
188  hs.update(new Uint8Array('abcdefg'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
189  const hashResult = hs.digest();
190  // 88A00F46836CD629D0B79DE98532AFDE3AEAD79A5C53E4848102F433046D0106
191  console.info(`hashResult: ${hashResult}`);
192  ```
193
194### digest<sup>12+</sup>
195
196digest(): string
197
198计算传给被哈希的所有数据的摘要。
199
200**系统能力**:SystemCapability.FileManagement.File.FileIO
201
202**错误码:**
203
204接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
205
206**示例:**
207
208  ```ts
209  // 创建哈希流
210  const hs = hash.createHash('sha256');
211  hs.update(new Uint8Array('1234567890'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
212  hs.update(new Uint8Array('abcdefg'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
213  const hashResult = hs.digest();
214  // 88A00F46836CD629D0B79DE98532AFDE3AEAD79A5C53E4848102F433046D0106
215  console.info(`hashResult: ${hashResult}`);
216  ```
217