Skip to content

Instantly share code, notes, and snippets.

@nekoya
Created March 5, 2013 07:20
Show Gist options
  • Save nekoya/5088592 to your computer and use it in GitHub Desktop.
Save nekoya/5088592 to your computer and use it in GitHub Desktop.
Perl Crypy::CBC (Blowfish) -> Python Crypto
import base64
from Crypto.Cipher import Blowfish
from binascii import unhexlify
from struct import pack
key = unhexlify('144a6b229633360207ff9c79016fc49426f1814727b663bc39df05df9a1892073e2812df9492c1e952aac68d1ddfefba635d3a33aba21535') # "thisiskey"
iv = '123abc45'
def enc(str):
plen = Blowfish.block_size - len(str) % Blowfish.block_size
padding = [plen] * plen
pad_str = str + pack('b' * plen, *padding)
cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
return base64.urlsafe_b64encode(cipher.encrypt(pad_str))
def dec(str):
plen = 4 - len(str) & 3
pad_str = str + '=' * plen
cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
dec = cipher.decrypt(base64.urlsafe_b64decode(pad_str))
num_padding = ord(dec[-1])
return dec[:(-1 * num_padding)]
assert enc('1234567') == '7Zbfy4S_B28='
assert enc('12345678') == '_V5IPxYq4omALzIyl10aMw=='
assert enc('hello world') == 'V6r02_ivXP2ChJ0DGd_7aw=='
assert dec('V6r02_ivXP2ChJ0DGd_7aw==') == 'hello world'
assert dec('V6r02_ivXP2ChJ0DGd_7aw') == dec('V6r02_ivXP2ChJ0DGd_7aw=') == dec('V6r02_ivXP2ChJ0DGd_7aw==') == dec('V6r02_ivXP2ChJ0DGd_7aw===')
use strict;
use warnings;
# http://stackoverflow.com/questions/14859006/using-pycrypto-to-decrypt-perl-encrypted-password
use Crypt::CBC;
my $key = shift or die '[usage] hex_key.pl key';
my $cipher = Crypt::CBC->new({
'key' => $key,
'cipher' => 'Blowfish',
'iv' => '12345678',
'regenerate_key' => 1,
'padding' => 'standard',
'prepend_iv' => 0,
});
$cipher->encrypt('ShutTheFuckUpAndWriteSomeCode');
print unpack('H*', $cipher->key), "\n";
@amp79
Copy link

amp79 commented May 2, 2018

thanks for your gist, i needed something like this but for DES,
to replace the hex_key pl, i added the below code.

def get_key(key):
    """Crypt::CBC decides that the key you give is not good enough
    and encrypts its further, but we do not use the new enc key entirely,
    we still have to keep the length, to the actual length of the key
    """
    nkey = md5(key.encode()).digest()
    if len(nkey) < len(key):
        nkey = get_key(nkey)
    else:
        nkey = nkey[:len(key)]
    return nkey

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment