将PasswordDeriveBytes功能转换为Python

时间:2018-04-20 00:17:15

标签: python powershell pycrypto password-hash kdf

我尝试使用pycryptodome的KDF模块在python中重新创建PowerShell的PasswordDeriveBytes方法。

我现在无法通过的主要任务是从PowerShell中获取Python中正确的DerivedKey结果。

参数:

password = '1234567890'
salt = '0987654321'
length = 16
iterations = 2

样本POWERSHELL代码:

$AsciiEncoder = New-Object System.Text.ASCIIEncoding;
$DerivedPass = New-Object System.Security.Cryptography.PasswordDeriveBytes('1234567890', $AsciiEncoder.GetBytes('0987654321'), "SHA1", 2);
[Byte[]] $KeyBytes = $DerivedPass.GetBytes(16);
-join($KeyBytes | ForEach { $_.ToString("X2")});

结果:

C937511EBDBE12C7A0FCC8D6CB42BEDC 

*注意:上面的PowerShell代码是从https://github.com/PowerShellMafia/PowerSploit/blob/master/ScriptModification/Out-EncryptedScript.ps1修改的。我正在尝试重新实现下面的Python代码中的功能。

PYTHON CODE:

from Crypto.Protocol import KDF
from Crypto.Hash import SHA1

def password_derive_key(password, salt, length, count):
    return KDF.PBKDF2(password, salt, length, count)

def main():
    derivedKey = password_derive_key('1234567890', '0987654321', 16, 2)
    print derivedKey.encode('hex')

if __name__ == "__main__":
    main()

结果:

5a3f103f5dc4558f8dca5d5b145ed0b4

我唯一可以想到的是" .GetBytes" PasswordDeriveBytes的方法产生的结果与pycryptodome的KDF模块不同。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

参数必须相同,在问题代码中迭代是不同的:

POWERSHELL迭代:2
System.Security.Cryptography.PasswordDeriveBytes('1234567890', $AsciiEncoder.GetBytes('0987654321'), "SHA1", 2);

PYTHON迭代:1000
derivedKey = password_derive_key('1234567890', '0987654321', 16, 1000)

确保每个都使用正确的编码。

注意:通过使用函数作为参数使调试更加困难,例如:$AsciiEncoder.GetBytes('0987654321')