1# @ohos.file.hash (File Hash Processing)
2
3The **FileHash** module implements hash processing on files.
4
5> **NOTE**
6>
7> 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.
8
9## Modules to Import
10
11```ts
12import { hash } from '@kit.CoreFileKit';
13```
14
15## Guidelines
16
17Before 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:
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
31For details about how to obtain the application sandbox path, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths).
32
33## hash.hash
34
35hash(path: string, algorithm: string): Promise<string>
36
37Calculates a hash value for a file. This API uses a promise to return the result.
38
39**Atomic service API**: This API can be used in atomic services since API version 11.
40
41**System capability**: SystemCapability.FileManagement.File.FileIO
42
43**Parameters**
44
45| Name   | Type  | Mandatory| Description                                                        |
46| --------- | ------ | ---- | ------------------------------------------------------------ |
47| path      | string | Yes  | Path of the file in the application sandbox.                            |
48| algorithm | string | Yes  | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
49
50**Return value**
51
52  | Type                   | Description                        |
53  | --------------------- | -------------------------- |
54  | Promise<string> | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
55
56**Error codes**
57
58For details about the error codes, see [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
59
60| ID| Error Message|
61| -------- | -------- |
62| 13900020 | Invalid argument |
63| 13900042 | Unknown error |
64
65**Example**
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
81Calculates a hash value for a file. This API uses an asynchronous callback to return the result.
82
83**Atomic service API**: This API can be used in atomic services since API version 11.
84
85**System capability**: SystemCapability.FileManagement.File.FileIO
86
87**Parameters**
88
89| Name   | Type                       | Mandatory| Description                                                        |
90| --------- | --------------------------- | ---- | ------------------------------------------------------------ |
91| path      | string                      | Yes  | Path of the file in the application sandbox.                            |
92| algorithm | string                      | Yes  | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
93| callback  | AsyncCallback<string> | Yes  | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
94
95**Error codes**
96
97For details about the error codes, see [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
98
99| ID| Error Message|
100| -------- | -------- |
101| 13900020 | Invalid argument |
102| 13900042 | Unknown error |
103
104**Example**
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
121Creates a **HashStream** instance, which can be used to generate a message digest (a hash value) using the given algorithm.
122
123**System capability**: SystemCapability.FileManagement.File.FileIO
124
125**Parameters**
126
127| Name| Type  | Mandatory| Description                                                        |
128| ------ | ------ | ---- | ------------------------------------------------------------ |
129| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
130
131**Return value**
132
133  | Type           | Description        |
134  | ------------- | ---------- |
135  | [HashStream](#hashstream12) | **HashStream** instance created.|
136
137**Error codes**
138
139For details about the error codes, see [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
140
141**Example**
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    // Create a readable stream.
150    const rs = fs.createReadStream(filePath);
151    // Create a hash stream.
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
168The **HashStream** class is a utility for creating a message digest of data. You can use [createHash](#hashcreatehash12) to create a **HashStream** instance.
169
170### update<sup>12+</sup>
171
172update(data: ArrayBuffer): void
173
174Updates the data for generating a message digest. This API can be called multiple times.
175
176**System capability**: SystemCapability.FileManagement.File.FileIO
177
178**Error codes**
179
180For details about the error codes, see [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
181
182**Example**
183
184  ```ts
185  // Create a hash stream.
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
198Generates a message digest.
199
200**System capability**: SystemCapability.FileManagement.File.FileIO
201
202**Error codes**
203
204For details about the error codes, see [Basic File IO Error Codes](errorcode-filemanagement.md#basic-file-io-error-codes).
205
206**Example**
207
208  ```ts
209  // Create a hash stream.
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