文件哈希處理

2024-01-23 16:31 更新

該模塊提供文件哈希處理能力,對文件內(nèi)容進(jìn)行哈希處理。

說明

本模塊首批接口從API version 9開始支持。后續(xù)版本的新增接口,采用上角標(biāo)單獨(dú)標(biāo)記接口的起始版本。

導(dǎo)入模塊

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

使用說明

使用該功能模塊對文件/目錄進(jìn)行操作前,需要先獲取其應(yīng)用沙箱路徑,獲取方式及其接口用法請參考:

Stage模型

  1. import UIAbility from '@ohos.app.ability.UIAbility';
  2. export default class EntryAbility extends UIAbility {
  3. onWindowStageCreate(windowStage) {
  4. let context = this.context;
  5. let pathDir = context.filesDir;
  6. }
  7. }

FA模型

  1. import featureAbility from '@ohos.ability.featureAbility';
  2. let context = featureAbility.getContext();
  3. context.getFilesDir().then((data) => {
  4. let pathDir = data;
  5. })

FA模型context的具體獲取方法參見FA模型。

Hash.hash

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

計(jì)算文件的哈希值,使用Promise異步回調(diào)。

系統(tǒng)能力:SystemCapability.FileManagement.File.FileIO

參數(shù):

參數(shù)名

類型

必填

說明

path

string

待計(jì)算哈希值文件的應(yīng)用沙箱路徑。

algorithm

string

哈希計(jì)算采用的算法??蛇x "md5"、"sha1" 或 "sha256"。建議采用安全強(qiáng)度更高的 "sha256"。

返回值:

類型

說明

Promise<string>

Promise對象。返回文件的哈希值。表示為十六進(jìn)制數(shù)字串,所有字母均大寫。

錯(cuò)誤碼:

以下錯(cuò)誤碼的詳細(xì)介紹請參見基礎(chǔ)文件IO錯(cuò)誤碼。

錯(cuò)誤碼ID

錯(cuò)誤信息

13900020

Invalid argument

13900042

Unknown error

示例:

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

Hash.hash

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

計(jì)算文件的哈希值,使用callback異步回調(diào)。

系統(tǒng)能力:SystemCapability.FileManagement.File.FileIO

參數(shù):

參數(shù)名

類型

必填

說明

path

string

待計(jì)算哈希值文件的應(yīng)用沙箱路徑。

algorithm

string

哈希計(jì)算采用的算法。可選 "md5"、"sha1" 或 "sha256"。建議采用安全強(qiáng)度更高的 "sha256"。

callback

AsyncCallback<string>

異步計(jì)算文件哈希操作之后的回調(diào)函數(shù)(其中給定文件哈希值表示為十六進(jìn)制數(shù)字串,所有字母均大寫)。

錯(cuò)誤碼:

以下錯(cuò)誤碼的詳細(xì)介紹請參見基礎(chǔ)文件IO錯(cuò)誤碼。

錯(cuò)誤碼ID

錯(cuò)誤信息

13900020

Invalid argument

13900042

Unknown error

示例:

  1. let filePath = pathDir + "/test.txt";
  2. Hash.hash(filePath, "sha256", (err, str) => {
  3. if (err) {
  4. console.error("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
  5. } else {
  6. console.info("calculate file hash succeed:" + str);
  7. }
  8. });
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號