首頁  >  文章  >  後端開發  >  如何使用 Python 檢查 sum.golang.org 中的 go.mod 雜湊值?

如何使用 Python 檢查 sum.golang.org 中的 go.mod 雜湊值?

王林
王林轉載
2024-02-09 12:10:08844瀏覽

如何使用 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刪除