我有一个 Ionic 7 项目,我需要根据相机捕获的照片计算哈希 SHA-256。
我已经有了捕获的图像,并且我有显示它的网址。
但是,我找不到任何函数可以让我计算包含捕获图像的文件的 SHA-256 哈希值。
希望你能帮助我。
我需要知道用相机拍照后是否存在计算或获取哈希 SHA-256 的方法。
您可以使用 WebCrypto API 计算 SHA-256 哈希值。
window.crypto.subtle.digest(
{
name: "SHA-256",
},
imageFileData // The image file data you want to calculate a hash for as an ArrayBuffer
)
.then(function(hash) {
// convert the hash to byte array
const hashArray = Array.from(new Uint8Array(hash));
// convert bytes to hex string
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
// use the hashHex string for comparison
})
.catch(function(err) {
console.error(err);
});
最后,我找到了解决我问题的方法:
import { Injectable } from '@angular/core';
import * as crypto from 'crypto-js';
@Injectable({
providedIn: 'root'
})
export class CryptoService {
constructor(
) { }
getHash256(imagePath:string){
this.toDataURL(imagePath).then(result=>{
const imagenBase64=result;
var encryptedData = crypto.SHA256(arrayBufferToWordArray(imagenBase64));//<-encryptedData contents the value of SHA-256 hash
return encryptedData.toString();
})
.catch(err => console.error(err));
return false;
}
toDataURL = async (url:string) => {
var res = await fetch(url);
var blob = await res.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.onerror = () => {
return reject(this);
};
reader.readAsArrayBuffer(blob);
});
}
}
function arrayBufferToWordArray(fileResult:any) {
var i8a = new Uint8Array(fileResult);
var byteArray = [];
for (var i = 0; i < i8a.length; i += 4) {
byteArray.push(i8a[i] << 24 | i8a[i + 1] << 16 | i8a[i + 2] << 8 | i8a[i + 3]);
}
return crypto.lib.WordArray.create(byteArray, i8a.length);
}
并调用该函数:
let hashImage=getHash256(string_with_path_of_image);