1# @ohos.file.hash (文件哈希处理) 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 9该模块提供文件哈希处理能力,对文件内容进行哈希处理。 10 11> **说明:** 12> 13> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 14 15## 导入模块 16 17```ts 18import { hash } from '@kit.CoreFileKit'; 19``` 20 21## 使用说明 22 23使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考: 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 37使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考:[应用上下文Context-获取应用文件路径](../../application-models/application-context-stage.md#获取应用文件路径)。 38 39## hash.hash 40 41hash(path: string, algorithm: string): Promise<string> 42 43计算文件的哈希值,使用Promise异步回调。 44 45**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 46 47**系统能力**:SystemCapability.FileManagement.File.FileIO 48 49**参数:** 50 51| 参数名 | 类型 | 必填 | 说明 | 52| --------- | ------ | ---- | ------------------------------| 53| path | string | 是 | 待计算哈希值文件的应用沙箱路径。 | 54| algorithm | string | 是 | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 | 55 56**返回值:** 57 58 | 类型 | 说明 | 59 | --------------------- | -------------------------- | 60 | Promise<string> | Promise对象。返回文件的哈希值。表示为十六进制数字串,所有字母均大写。 | 61 62**错误码:** 63 64以下错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 65 66| 错误码ID | 错误信息 | 67| -------- | -------- | 68| 13900020 | Invalid argument. | 69| 13900042 | Unknown error. | 70 71**示例:** 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<string>): void 86 87计算文件的哈希值,使用callback异步回调。 88 89**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 90 91**系统能力**:SystemCapability.FileManagement.File.FileIO 92 93**参数:** 94 95| 参数名 | 类型 | 必填 | 说明 | 96| --------- | --------------------------- | ---- | ------------------------------------------------------------ | 97| path | string | 是 | 待计算哈希值文件的应用沙箱路径。 | 98| algorithm | string | 是 | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 | 99| callback | AsyncCallback<string> | 是 | 异步计算文件哈希操作之后的回调函数(其中给定文件哈希值表示为十六进制数字串,所有字母均大写)。 | 100 101**错误码:** 102 103以下错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 104 105| 错误码ID | 错误信息 | 106| -------- | -------- | 107| 13900020 | Invalid argument. | 108| 13900042 | Unknown error. | 109 110**示例:** 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 127创建并返回 HashStream 对象,该对象可用于使用给定的 algorithm 生成哈希摘要。 128 129**系统能力**:SystemCapability.FileManagement.File.FileIO 130 131**参数:** 132 133| 参数名 | 类型 | 必填 | 说明 | 134| ------ | ------ | ---- | ------------------------------------------------------------ | 135| algorithm | string | 是 | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 | 136 137**返回值:** 138 139 | 类型 | 说明 | 140 | ------------- | ---------- | 141 | [HashStream](#hashstream12) | HashStream 类的实例。 | 142 143**错误码:** 144 145以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 146 147| 错误码ID | 错误信息 | 148| ---------------------------- | ---------- | 149| 401 | Parameter error. | 150| 13900020 | Invalid argument. | 151| 13900042 | Unknown error. | 152 153**示例:** 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 // 创建文件可读流 162 const rs = fs.createReadStream(filePath); 163 // 创建哈希流 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 180HashStream 类是用于创建数据的哈希摘要的实用工具。由 [createHash](#hashcreatehash12) 接口获得。 181 182### update<sup>12+</sup> 183 184update(data: ArrayBuffer): void 185 186使用给定的 data 更新哈希内容,可多次调用。 187 188**系统能力**:SystemCapability.FileManagement.File.FileIO 189 190**参数:** 191 192| 参数名 | 类型 | 必填 | 说明 | 193| ---- | ----------- | -- | ----------------- | 194| data | ArrayBuffer | 是 | 待计算哈希值的数据。| 195 196**错误码:** 197 198以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 199 200| 错误码ID | 错误信息 | 201| ---------------------------- | ---------- | 202| 401 | Parameter error. | 203| 13900042 | Unknown error. | 204 205**示例:** 206 207 ```ts 208 // 创建哈希流 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 221计算传给被哈希的所有数据的摘要。 222 223**系统能力**:SystemCapability.FileManagement.File.FileIO 224 225**返回值:** 226 227| 类型 | 说明 | 228| ------ | --------------------------------------------------------- | 229| string | 返回数据的哈希值。该哈希值表示为十六进制数字串,所有字母均大写。| 230 231**错误码:** 232 233以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 234 235| 错误码ID | 错误信息 | 236| ---------------------------- | ---------- | 237| 401 | Parameter error. | 238| 13900042 | Unknown error. | 239 240**示例:** 241 242 ```ts 243 // 创建哈希流 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 ```