首页 > 解决方案 > 如何使用加密从字符串创建 sha256

问题描述

所以我试图按照这个代码示例创建一个随机数

   let randomString = uuid();

  // create a sha256 of randomString, this will be the nonce sent to apple during authentication
  const nonce = await Crypto.digestStringAsync(
    Crypto.CryptoDigestAlgorithm.SHA256,
    randomString
  );

但是,此示例适用于世博会的“加密”版本,我正在使用 node.js 中内置的加密并尝试执行此操作

    let randomString = uuid(); // <--- this just creates a random string for me

   const nonce = await crypto
      .createHmac('sha256', randomString)
      .update(uuid())
      .digest('string');

但这似乎并没有以我需要的格式创建随机数。有谁知道世博会的加密和 node.js 中内置的加密的人知道我做错了什么吗?我很确定我只是没有以与 expo 加密示例相同的方式使用 nodejs 加密,所以也许知道它们的人可以告诉我那个 expo 加密示例的 nodejs 加密版本是什么?

标签: node.jsexpo

解决方案


摘要字符串的 Expo 默认格式为十六进制 ( doc )

options CryptoDigestOptions 摘要字符串的格式。默认为:CryptoDigestOptions.HEX

所以你只需要更改.digest("string").digest("hex")

let randomString = uuid()

const nonce = await crypto
  .createHmac("sha256", randomString)
  .update(uuid())
  .digest("hex")

推荐阅读