简体   繁体   English

Office 脚本中的 SHA-256 返回一个空的 object

[英]SHA-256 in Office Scripts is returning an empty object

I found some code online to create use SHA-256 in JavaScript. But I'm not able to get it working in Office Scripts.我在 JavaScript 中找到了一些在线创建使用 SHA-256 的代码。但我无法在 Office 脚本中使用它。

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?我究竟做错了什么?

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. sha256() function 是一个异步 function。我试图从主 function 调用它,默认情况下它不是异步的。 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.所以为了调用它,我需要在主 function 之前添加async关键字。当我调用sha256()时,我需要使用await关键字。

    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"通过此更新,我知道在控制台中显示以下 output:“6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM