Reputation: 1354
I found some code online to create use SHA-256 in JavaScript. But I'm not able to get it working in Office Scripts.
This is my code below:
function main(workbook: ExcelScript.Workbook) {
let temp = sha256("abc123")
console.log(temp)
}
async function sha256(message:string) {
// encode as UTF-8
const msgBuffer = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
return hashHex;
}
When I look at the console I see {}
. From what I can tell, it should be working. What am I doing wrong?
Upvotes: 0
Views: 274
Reputation: 1354
Ah, it looks like the fix is relatively simple. The sha256()
function is an async function. And I'm trying to call it from the main function which by default is not async. So in order to call it, I need to add the async
keyword before the main function. And when I call sha256()
I need to use the await
keyword.
async function main(workbook: ExcelScript.Workbook) {
let temp = await sha256("abc123")
console.log(temp)
}
async function sha256(message:string) {
// encode as UTF-8
const msgBuffer = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
return hashHex;
}
With this update I know show the following output in the console: "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090"
Upvotes: 1