首页  >  文章  >  后端开发  >  如何使用 Python 检查 sum.golang.org 中的 go.mod 哈希值?

如何使用 Python 检查 sum.golang.org 中的 go.mod 哈希值?

王林
王林转载
2024-02-09 12:10:08846浏览

如何使用 Python 检查 sum.golang.org 中的 go.mod 哈希值?

php小编西瓜在这里为大家介绍如何使用Python检查sum.golang.org中的go.mod哈希值。sum.golang.org是一个用于验证Go模块的哈希值的官方服务,它可以帮助开发者确保模块的完整性和安全性。通过使用Python的requests库和hashlib库,我们可以轻松地获取并比对go.mod文件的哈希值,从而确保我们使用的模块是可信的。下面就让我们一起来看看具体的实现步骤吧。

问题内容

我需要验证 sum.golang.org 提供的 go.mod 文件的哈希值。我需要使用 PYTHON。

例如 - https://sum.golang.org/lookup/github.com/gin-gonic/[电子邮件受保护]文件 https://proxy.golang.org/github.com/gin-gonic/gin/@v/v1.6.2.mod

我们在这里:

import base64
import requests
import hashlib
import os

# some tmp file
tmp_file = os.path.abspath(os.path.dirname(__file__)) + '/tmp.mod'

# url for sumdb
link_sum_db = 'https://sum.golang.org/lookup/github.com/gin-gonic/[email protected]'
# our line:
# github.com/gin-gonic/gin v1.6.2/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
hash_from_sumdb = b'75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M='
print(hash_from_sumdb)
# b'75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M='

# download the file
f_url = 'https://proxy.golang.org/github.com/gin-gonic/gin/@v/v1.6.2.mod'
f_url_content = requests.get(f_url).content
with open(tmp_file, 'wb') as f:
    f.write(f_url_content)

with open(tmp_file, 'rb') as f:
    f_file_content = f.read()

# calculate hash from local tmp file
hash_from_file = base64.b64encode(hashlib.sha256(f_file_content).digest())
print(hash_from_file)
# b'x9T1RkIbnNSJydQMU9l8mvXfhBIkDhO3TTHCbOVG4Go='
# and it fails =(
assert hash_from_file == hash_from_sumdb

请帮帮我。我知道 go 命令,但我需要在这里使用 python ... 我读过这个主题,但没有帮助 =(

解决方法

事情似乎比这更复杂一些。 我关注了您提到的主题,并在 这个答案。 另外,如果您参考 该函数源码,可以看到go模块中使用的hash是如何实现的。

此版本有效:

import hashlib
import base64

def calculate_sha256_checksum(data):
    sha256_hash = hashlib.sha256()
    sha256_hash.update(data.encode('utf-8'))
    return sha256_hash.digest()

# Specify the file path
file_path = 'go.mod'

# Read the file content
with open(file_path, 'r') as file:
    file_content = file.read()

# Calculate the SHA256 checksum of the file content
checksum1 = calculate_sha256_checksum(file_content)

# Format the checksum followed by two spaces, filename, and a new line
formatted_string = f'{checksum1.hex()}  {file_path}\n'

# Calculate the SHA256 checksum of the formatted string
checksum2 = calculate_sha256_checksum(formatted_string)

# Convert the checksum to base64
base64_checksum = base64.b64encode(checksum2).decode('utf-8')

print(base64_checksum)

以上是如何使用 Python 检查 sum.golang.org 中的 go.mod 哈希值?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除