在python和powershell中读取文件

在python和powershell中读取文件,python,powershell,hash,sha1,Python,Powershell,Hash,Sha1,我正在将大量脚本从PowerShell迁移到Python,以实现更大的跨平台兼容性。但是我在读取文件和获取相同的哈希时遇到了问题。在PowerShell中,我使用的函数是: Function Get-Hash { param ( [string]$someText ) $hasher = new-object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider $utf8 = new-object -TypeN

我正在将大量脚本从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()
使用这两个函数,我可以得到相同的字符串哈希值。例如,执行此操作时哈希匹配:

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()

散列结果不一样。我想这是我读取文件的方式,但我似乎无法让它们匹配。

你试过脱衣吗?像
文件\u content.strip()


或者尝试删除换行符:
''.join((如果c!='\n'),则文件内容中的c代表c)
是否尝试删除?像
文件\u content.strip()


或者尝试删除换行符:
''.join((如果c!='\n'),文件内容中的c代表c)

为什么要在对文件进行哈希运算之前对其进行编码?将其作为二进制数据读取,并对原始二进制数据进行散列。您能详细说明一下吗?我在Python“哈希前必须对Unicode对象进行编码”中遇到一个错误,
hashlib.sha1(文件内容).hexdigest().upper()
hashlib.sha1(open('c:\\path\\to\\file.txt','rb').read()).hexdigest().upper()
但您可能仍然无法获得相同的值,因为您正在对PowerShell中包含文件数据的编码字符串进行哈希运算,而在这里,您正在对文件的二进制内容进行哈希运算,这是哈希文件的推荐方法。为什么要在对文件进行哈希运算之前对其进行编码?将其作为二进制数据读取,并对原始二进制数据进行散列。您能详细说明一下吗?我在Python“哈希前必须对Unicode对象进行编码”中遇到一个错误,
hashlib.sha1(文件内容).hexdigest().upper()
hashlib.sha1(open('c:\\path\\to\\file.txt','rb').read()).hexdigest().upper()
但您可能仍然无法获得相同的值,因为您正在对PowerShell中包含文件数据的编码字符串进行哈希运算,而在这里,您正在对文件的二进制内容进行哈希运算,这是对文件进行哈希运算的推荐方法。strip()提供的哈希值与未提供的哈希值相同。strip()删除换行符会提供不同的哈希值,但与Powershell函数不同..strip()提供的哈希值与未提供的哈希值相同。strip()删除换行符会提供不同的哈希值,但与Powershell函数不同。