• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.file.hash (File Hash Processing)
2<!--Kit: Core File Kit-->
3<!--Subsystem: FileManagement-->
4<!--Owner: @wangke25; @gsl_1234; @wuchengjun5-->
5<!--Designer: @gsl_1234; @wangke25-->
6<!--Tester: @liuhonggang123; @yue-ye2; @juxiaopang-->
7<!--Adviser: @foryourself-->
8
9The **FileHash** module implements hash processing on files.
10
11> **NOTE**
12>
13> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
14
15## Modules to Import
16
17```ts
18import { hash } from '@kit.CoreFileKit';
19```
20
21## Guidelines
22
23Before using the APIs provided by this module to perform operations on a file or directory, obtain the application sandbox path of the file or directory as follows:
24
25  ```ts
26  import { UIAbility } from '@kit.AbilityKit';
27  import { window } from '@kit.ArkUI';
28
29  export default class EntryAbility extends UIAbility {
30    onWindowStageCreate(windowStage: window.WindowStage) {
31      let context = this.context;
32      let pathDir = context.filesDir;
33    }
34  }
35  ```
36
37For details about how to obtain the application sandbox path, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths).
38
39## hash.hash
40
41hash(path: string, algorithm: string): Promise&lt;string&gt;
42
43Calculates a hash value for a file. This API uses a promise to return the result.
44
45**Atomic service API**: This API can be used in atomic services since API version 11.
46
47**System capability**: SystemCapability.FileManagement.File.FileIO
48
49**Parameters**
50
51| Name   | Type  | Mandatory| Description                          |
52| --------- | ------ | ---- | ------------------------------|
53| path      | string | Yes  | Path of the file in the application sandbox.|
54| algorithm | string | Yes  | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
55
56**Return value**
57
58  | Type                   | Description                        |
59  | --------------------- | -------------------------- |
60  | Promise&lt;string&gt; | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
61
62**Error codes**
63
64For details about the error codes, see [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
65
66| ID| Error Message|
67| -------- | -------- |
68| 13900020 | Invalid argument. |
69| 13900042 | Unknown error. |
70
71**Example**
72
73  ```ts
74  import { BusinessError } from '@kit.BasicServicesKit';
75  let filePath = pathDir + "/test.txt";
76  hash.hash(filePath, "sha256").then((str: string) => {
77    console.info("calculate file hash succeed:" + str);
78  }).catch((err: BusinessError) => {
79    console.error("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
80  });
81  ```
82
83## hash.hash
84
85hash(path: string, algorithm: string, callback: AsyncCallback&lt;string&gt;): void
86
87Calculates a hash value for a file. This API uses an asynchronous callback to return the result.
88
89**Atomic service API**: This API can be used in atomic services since API version 11.
90
91**System capability**: SystemCapability.FileManagement.File.FileIO
92
93**Parameters**
94
95| Name   | Type                       | Mandatory| Description                                                        |
96| --------- | --------------------------- | ---- | ------------------------------------------------------------ |
97| path      | string                      | Yes  | Path of the file in the application sandbox.                            |
98| algorithm | string                      | Yes  | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
99| callback  | AsyncCallback&lt;string&gt; | Yes  | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
100
101**Error codes**
102
103For details about the error codes, see [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
104
105| ID| Error Message|
106| -------- | -------- |
107| 13900020 | Invalid argument. |
108| 13900042 | Unknown error. |
109
110**Example**
111
112  ```ts
113  import { BusinessError } from '@kit.BasicServicesKit';
114  let filePath = pathDir + "/test.txt";
115  hash.hash(filePath, "sha256", (err: BusinessError, str: string) => {
116    if (err) {
117      console.error("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
118    } else {
119      console.info("calculate file hash succeed:" + str);
120    }
121  });
122  ```
123## hash.createHash<sup>12+</sup>
124
125createHash(algorithm: string): HashStream
126
127Creates a **HashStream** instance, which can be used to generate a message digest (a hash value) using the given algorithm.
128
129**System capability**: SystemCapability.FileManagement.File.FileIO
130
131**Parameters**
132
133| Name| Type  | Mandatory| Description                                                        |
134| ------ | ------ | ---- | ------------------------------------------------------------ |
135| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
136
137**Return value**
138
139  | Type           | Description        |
140  | ------------- | ---------- |
141  | [HashStream](#hashstream12) | **HashStream** instance created.|
142
143**Error codes**
144
145For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
146
147| ID                    | Error Message       |
148| ---------------------------- | ---------- |
149| 401 | Parameter error. |
150| 13900020 | Invalid argument. |
151| 13900042 | Unknown error. |
152
153**Example**
154
155  ```ts
156  // pages/xxx.ets
157  import { fileIo as fs } from '@kit.CoreFileKit';
158
159  function hashFileWithStream() {
160    const filePath = pathDir + "/test.txt";
161    // Create a readable stream.
162    const rs = fs.createReadStream(filePath);
163    // Create a hash stream.
164    const hs = hash.createHash('sha256');
165    rs.on('data', (emitData) => {
166      const data = emitData?.data;
167      hs.update(new Uint8Array(data?.split('').map((x: string) => x.charCodeAt(0))).buffer);
168    });
169    rs.on('close', async () => {
170      const hashResult = hs.digest();
171      const fileHash = await hash.hash(filePath, 'sha256');
172      console.info(`hashResult: ${hashResult}, fileHash: ${fileHash}`);
173    });
174  }
175  ```
176
177
178## HashStream<sup>12+</sup>
179
180The **HashStream** class is a utility for creating a message digest of data. You can use [createHash](#hashcreatehash12) to create a **HashStream** instance.
181
182### update<sup>12+</sup>
183
184update(data: ArrayBuffer): void
185
186Updates the data for generating a message digest. This API can be called multiple times.
187
188**System capability**: SystemCapability.FileManagement.File.FileIO
189
190**Parameters**
191
192| Name| Type| Mandatory| Description|
193| ---- | ----------- | -- | ----------------- |
194| data | ArrayBuffer | Yes| Data to be calculated.|
195
196**Error codes**
197
198For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
199
200| ID                    | Error Message       |
201| ---------------------------- | ---------- |
202| 401 | Parameter error. |
203| 13900042 | Unknown error. |
204
205**Example**
206
207  ```ts
208  // Create a hash stream.
209  const hs = hash.createHash('sha256');
210  hs.update(new Uint8Array('1234567890'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
211  hs.update(new Uint8Array('abcdefg'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
212  const hashResult = hs.digest();
213  // 88A00F46836CD629D0B79DE98532AFDE3AEAD79A5C53E4848102F433046D0106
214  console.info(`hashResult: ${hashResult}`);
215  ```
216
217### digest<sup>12+</sup>
218
219digest(): string
220
221Generates a message digest.
222
223**System capability**: SystemCapability.FileManagement.File.FileIO
224
225**Return value**
226
227| Type| Description|
228| ------ | --------------------------------------------------------- |
229| string | Hash value, which is a hexadecimal string consisting of digits and uppercase letters.|
230
231**Error codes**
232
233For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
234
235| ID                    | Error Message       |
236| ---------------------------- | ---------- |
237| 401 | Parameter error. |
238| 13900042 | Unknown error. |
239
240**Example**
241
242  ```ts
243  // Create a hash stream.
244  const hs = hash.createHash('sha256');
245  hs.update(new Uint8Array('1234567890'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
246  hs.update(new Uint8Array('abcdefg'?.split('').map((x: string) => x.charCodeAt(0))).buffer);
247  const hashResult = hs.digest();
248  // 88A00F46836CD629D0B79DE98532AFDE3AEAD79A5C53E4848102F433046D0106
249  console.info(`hashResult: ${hashResult}`);
250  ```
251