我正在将一堆脚本从PowerShell迁移到Python,以实现更大的跨平台兼容性。但我在读取文件和获取相同的哈希时遇到了问题。在PowerShell中,我使用的函数是:
Function Get-Hash {
param (
[string]$someText
)
$hasher = new-object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
return ([System.BitConverter]::ToString($hasher.ComputeHash($utf8.GetBytes($someText)))).Replace("-","")
}
在Python中,我这样做:
import hashlib
hashlib.sha1(some_text.encode('utf-8')).hexdigest().upper()
使用这两个函数,我可以得到字符串的相同哈希值。例如,执行此操作时哈希匹配:
#Powershell:
get-hash -someText 'testing'
#Python:
hashlib.sha1('testing'.encode('utf-8')).hexdigest().upper()
但是,当我试图读入一个有换行符的文件时,问题出现了:
#Powershell:
$fileContent = get-content 'c:\path\to\file.txt'
get-hash -someText $fileContent
#Python:
with open('c:\path\to\file.txt', 'r', encoding='utf-8') as file:
file_content = file.read()
hashlib.sha1(file_content.encode('utf-8')).hexdigest().upper()
散列结果不一样。我想这是我读文件的方式,但我似乎无法让它们匹配。你知道吗
你试过脱衣吗?比如
file_content.strip()
?或者尝试删除换行:
''.join((c for c in file_content if c != '\n'))
相关问题 更多 >
编程相关推荐