You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Osmosis链block_hash转换求助:Uint8Array无法转为有效可读哈希

从Osmosis链获取区块哈希的转换问题

我正尝试从Osmosis链获取block_hash等数据,遇到的问题是得到的是Uint8Array,无法转换为可读的字符串/哈希。

JS应用返回的响应

blockId: {
    hash: Uint8Array(32) [
       91, 215, 254, 180,  87, 180, 160, 121,
       12,  47, 235,  35, 219, 203,  27,  45,
      102, 213,  50,  40,  54, 194,  33,  28,
      231, 139, 216, 246,  45,  73,  58, 188
    ],
    partSetHeader: { total: 2, hash: [Uint8Array] }
}

Postman返回的响应

"block_id": {
   "hash": "mHyghR6nW+Mb+2SZ5DYTw6xfLO+IlrMW3vMh9nXo394=",
   "part_set_header": {
      "total": 2,
      "hash": "u78nOYgp5bAZXmymTBFPbNIPxI+1NuRhi+I32Z5pSKY="
   }
}

尝试的转换代码及结果

我用以下代码转换Uint8Array:

const string = new TextDecoder().decode(hash);
console.log(string);

得到乱码:

ڨ9�$Օka�
�Ց���ewf�§�qA�♥߂��

另外,mHyghR6nW+Mb+2SZ5DYTw6xfLO+IlrMW3vMh9nXo394=显然不是有效的区块链交易哈希,有效哈希格式类似:BE2E8DFB4489D0349C78BC30D14802DE88FDF581F8DB6B6FAFA9EB6157646C07。

请问这是否属于加密?如果是,该如何解密转换为有效哈希?


解决方案

这不是加密,只是数据编码格式的问题:

  1. Postman返回的是Base64编码:你看到的mHyghR6nW+Mb+2SZ5DYTw6xfLO+IlrMW3vMh9nXo394=是32字节哈希的Base64编码结果,而区块链常用的是十六进制编码(即你提到的类似BE2E8DFB...的格式)。

  2. Uint8Array转十六进制哈希的方法:
    直接遍历Uint8Array的每个元素,转换为两位的十六进制字符串后拼接即可,示例代码:

    function uint8ArrayToHex(hashUint8) {
      return Array.from(hashUint8)
        .map(byte => byte.toString(16).padStart(2, '0'))
        .join('')
        .toUpperCase();
    }
    
    // 使用示例
    const hash = new Uint8Array([91, 215, 254, 180, 87, 180, 160, 121, 12, 47, 235, 35, 219, 203, 27, 45, 102, 213, 50, 40, 54, 194, 33, 28, 231, 139, 216, 246, 45, 73, 58, 188]);
    console.log(uint8ArrayToHex(hash)); // 输出 5BD7FEB457B4A0790C2FEB23DBCB1B2D66D5322836C2211CE78BD8F62D493ABC
    
  3. 为什么TextDecoder解码会乱码:哈希是二进制数据,并非UTF-8编码的文本内容,用TextDecoder解码自然会得到乱码,这是错误的转换方式。

  4. Base64转十六进制的方法:如果需要把Postman返回的Base64字符串转成十六进制哈希,先将Base64转成Uint8Array,再用上述方法转十六进制:

    function base64ToHex(base64Str) {
      const binaryStr = atob(base64Str);
      const uint8Array = new Uint8Array(binaryStr.length);
      for (let i = 0; i < binaryStr.length; i++) {
        uint8Array[i] = binaryStr.charCodeAt(i);
      }
      return uint8ArrayToHex(uint8Array);
    }
    
    // 使用示例
    const base64Hash = "mHyghR6nW+Mb+2SZ5DYTw6xfLO+IlrMW3vMh9nXo394=";
    console.log(base64ToHex(base64Hash)); // 输出相同的十六进制哈希
    

内容的提问来源于stack exchange,提问作者mitrandir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:20:27