harmony 鸿蒙@ohos.file.hash (文件哈希处理)

2023-02-03 浏览 (941)

@ohos.file.hash (文件哈希处理)

该模块提供文件哈希处理能力,对文件内容进行哈希处理。

说明:

本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

import Hash from '@ohos.file.hash';

使用说明

使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考:

Stage模型

import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    let context = this.context;
    let pathDir = context.filesDir;
  }
}

FA模型

import featureAbility from '@ohos.ability.featureAbility';

let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
  let pathDir = data;
})

FA模型context的具体获取方法参见FA模型

Hash.hash

hash(path: string, algorithm: string): Promise<string>

计算文件的哈希值,使用Promise异步回调。

系统能力:SystemCapability.FileManagement.File.FileIO

参数:

参数名类型必填说明
pathstring待计算哈希值文件的应用沙箱路径。
algorithmstring哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。

返回值:

类型说明
Promise<string>Promise对象。返回文件的哈希值。表示为十六进制数字串,所有字母均大写。

错误码:

以下错误码的详细介绍请参见基础文件IO错误码

错误码ID错误信息
13900020Invalid argument
13900042Unknown error

示例:

let filePath = pathDir + "/test.txt";
Hash.hash(filePath, "sha256").then((str: string) => {
  console.info("calculate file hash succeed:" + str);
}).catch((err: BusinessError) => {
  console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
});

Hash.hash

hash(path: string, algorithm: string, callback: AsyncCallback<string>): void

计算文件的哈希值,使用callback异步回调。

系统能力:SystemCapability.FileManagement.File.FileIO

参数:

参数名类型必填说明
pathstring待计算哈希值文件的应用沙箱路径。
algorithmstring哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256"。
callbackAsyncCallback<string>异步计算文件哈希操作之后的回调函数(其中给定文件哈希值表示为十六进制数字串,所有字母均大写)。

错误码:

以下错误码的详细介绍请参见基础文件IO错误码

错误码ID错误信息
13900020Invalid argument
13900042Unknown error

示例:

let filePath = pathDir + "/test.txt";
Hash.hash(filePath, "sha256", (err: BusinessError, str: string) => {
  if (err) {
    console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
  } else {
    console.info("calculate file hash succeed:" + str);
  }
});

你可能感兴趣的鸿蒙文章

harmony 鸿蒙接口

harmony 鸿蒙系统公共事件定义(待停用)

harmony 鸿蒙系统公共事件定义

harmony 鸿蒙开发说明

harmony 鸿蒙企业设备管理概述(仅对系统应用开放)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager模块)

harmony 鸿蒙@ohos.distributedBundle (分布式包管理)

harmony 鸿蒙@ohos.bundle (Bundle模块)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/e99506eb7ca74a56ae7fac6244b950f5