1# @ohos.file.hash (文件哈希处理) 2 3该模块提供文件哈希处理能力,对文件内容进行哈希处理。 4 5> **说明:** 6> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 7> 本模块支持对错误码进行处理,错误码及其适配方式[参考文档](../errorcodes/errorcode-filemanagement.md#错误码适配指导)。 8 9## 导入模块 10 11```js 12import Hash from '@ohos.file.hash'; 13``` 14 15## 使用说明 16 17使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考: 18 19**Stage模型** 20 21 ```js 22import UIAbility from '@ohos.app.ability.UIAbility'; 23 24export default class EntryAbility extends UIAbility { 25 onWindowStageCreate(windowStage) { 26 let context = this.context; 27 let pathDir = context.filesDir; 28 } 29} 30 ``` 31 32**FA模型** 33 34 ```js 35 import featureAbility from '@ohos.ability.featureAbility'; 36 37 let context = featureAbility.getContext(); 38 context.getFilesDir().then((data) => { 39 let pathDir = data; 40 }) 41 ``` 42 43FA模型context的具体获取方法参见[FA模型](js-apis-inner-app-context.md#Context模块)。 44 45## Hash.hash 46 47hash(path: string, algorithm: string): Promise<string> 48 49计算文件的哈希值,使用Promise异步回调。 50 51**系统能力**:SystemCapability.FileManagement.File.FileIO 52 53**参数:** 54 55| 参数名 | 类型 | 必填 | 说明 | 56| --------- | ------ | ---- | ------------------------------------------------------------ | 57| path | string | 是 | 待计算哈希值文件的应用沙箱路径。 | 58| algorithm | string | 是 | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 | 59 60**返回值:** 61 62 | 类型 | 说明 | 63 | --------------------- | -------------------------- | 64 | Promise<string> | Promise对象。返回文件的哈希值。表示为十六进制数字串,所有字母均大写。 | 65 66**示例:** 67 68 ```js 69 let filePath = pathDir + "/test.txt"; 70 Hash.hash(filePath, "sha256").then((str) => { 71 console.info("calculate file hash succeed:" + str); 72 }).catch((err) => { 73 console.info("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**系统能力**:SystemCapability.FileManagement.File.FileIO 84 85**参数:** 86 87| 参数名 | 类型 | 必填 | 说明 | 88| --------- | --------------------------- | ---- | ------------------------------------------------------------ | 89| path | string | 是 | 待计算哈希值文件的应用沙箱路径。 | 90| algorithm | string | 是 | 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。 | 91| callback | AsyncCallback<string> | 是 | 异步计算文件哈希操作之后的回调函数(其中给定文件哈希值表示为十六进制数字串,所有字母均大写)。 | 92 93**示例:** 94 ```js 95 let filePath = pathDir + "/test.txt"; 96 Hash.hash(filePath, "sha256", (err, str) => { 97 if (err) { 98 console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); 99 } else { 100 console.info("calculate file hash succeed:" + str); 101 } 102 }); 103 ``` 104