我正在尝试解密存储在文件中的密码短语。加密是使用Perl :: CBC模块完成的,但我需要为Python脚本解密它。坦率地说,我对加密算法知之甚少(或其他任何事情)。
密码短语的加密方式如下:
use Crypt::CBC;
my $key = '0123456789';
my $iv = '$KJh#(}q';
my $cipher = Crypt::CBC->new(
-key => $key,
-cipher => 'Blowfish',
-header => 'none',
-iv => $iv,
);
my $passphrase = 'You have decrypted the passphrase.';
my $hex_encrypted = $cipher->encrypt_hex($passphrase);
给出加密的密码:9033c838e4418fbdc50a9fc0813745296d195d59954008f94b2b36a8e65dca959686206960a7828a
现在,我需要在Python脚本中使用它(使用Python 2.7)。天真,我希望这会奏效:
from Crypto.Cipher import Blowfish
from binascii import hexlify, unhexlify
perl_pass = unhexlify('9033c838e4418fbdc50a9fc0813745296d195d59954008f94b2b36a8e65dca959686206960a7828a')
key = '0123456789'
iv = '$KJh#(}q'
print Blowfish.new(key, Blowfish.MODE_CBC, iv).decrypt(perl_pass)
但这似乎只会造成一堆不可打印的垃圾。我玩了一下但没有成功。我不太确定我需要做什么来成功解密密码。
答案 0 :(得分:1)
你给Crypt :: CBC的“密钥”实际上是一个密码,从中生成“文字密钥”; Crypto.Cipher.Blowfish需要该文字密钥,而不是密码。您可以从Perl程序中以十六进制格式打印生成的密钥,然后在Python中使用它:
use Crypt::CBC;
my $key = '0123456789';
my $iv = '$KJh#(}q';
my $cipher = Crypt::CBC->new(
-key => $key,
-cipher => 'Blowfish',
-header => 'none',
-iv => $iv,
);
my $passphrase = "You have decrypted the passphrase.";
my $hex_encrypted = $cipher->encrypt_hex($passphrase);
print unpack('H*', $cipher->key()), "\n";
-
$ perl perl_crypt_cbc.pl
781e5e245d69b566979b86e28d23f2c78e938564cd1410f0ec1c1781466a6738bab0a6ed984c75ab34c68bbf7558077714043c5bdb959e46
-
from Crypto.Cipher import Blowfish
from binascii import hexlify, unhexlify
perl_pass = unhexlify("9033c838e4418fbdc50a9fc0813745296d195d59954008f94b2b36a8e65dca959686206960a7828a")
key = unhexlify("781e5e245d69b566979b86e28d23f2c78e938564cd1410f0ec1c1781466a6738bab0a6ed984c75ab34c68bbf7558077714043c5bdb959e46")
iv = '$KJh#(}q'
print Blowfish.new(key, Blowfish.MODE_CBC, iv).decrypt(perl_pass)
-
python python_crypt_cbc.py
You have decrypted the passphrase.
请注意,最后会有一些不可打印的字符:Blowfish加密的字符串必须是8个字节的倍数,因此Perl会默默地填充它。它填充的字节是填充的长度:在这种情况下,填充六个字节,因此它们每个都是0x06。您可以轻松删除它们:
from Crypto.Cipher import Blowfish
from binascii import hexlify, unhexlify
perl_pass = unhexlify("9033c838e4418fbdc50a9fc0813745296d195d59954008f94b2b36a8e65dca959686206960a7828a")
key = unhexlify("781e5e245d69b566979b86e28d23f2c78e938564cd1410f0ec1c1781466a6738bab0a6ed984c75ab34c68bbf7558077714043c5bdb959e46")
iv = '$KJh#(}q'
num_padding = ord(Blowfish.new(key, Blowfish.MODE_CBC, iv).decrypt(perl_pass)[-1])
print Blowfish.new(key, Blowfish.MODE_CBC, iv).decrypt(perl_pass)[:(-1*num_padding)]