Search code examples
pythonpycryptodome

Use key as byte array for DES3 in python


I have a key and IV for DES3 as byte array (generated by C#):

var _algo = TripleDES.Create();
_algo.GenerateIV();
_algo.GenerateKey();
Console.WriteLine(string.Join(", ", _algo.IV));
Console.WriteLine(string.Join(", ", _algo.Key));

I get these values for example:

[220, 138, 91, 56, 76, 81, 217, 70]
[88, 221, 70, 78, 149, 105, 62, 50, 93, 32, 72, 240, 54, 53, 153, 41, 39, 135, 78, 19, 216, 208, 180, 50]

How do I properly use the key to decode the message in Python? I'm trying:

from Crypto.Cipher import DES3

codedText = "hvAjofLh4mc="

iv = [220, 138, 91, 56, 76, 81, 217, 70]
key = [88, 221, 70, 78, 149, 105, 62, 50, 93, 32, 72, 240, 54, 53, 153, 41, 39, 135, 78, 19, 216, 208, 180, 50]
cipher_encrypt = DES3.new(bytearray(key), DES3.MODE_CBC, bytearray(iv))
v = cipher_encrypt.decrypt(codedText)

This gives me

TypeError: Object type <class 'str'> cannot be passed to C code

But I think I am doing something wrong with the keys.

The code I used to generate the keys/message in C#: https://dotnetfiddle.net/PXcNhl


Solution

  • To summarize some findings from the comments:

    • For crypto libraries under Python 3 the input and output need to be byte strings or byte literals (b"something").
    • While for plaintext .encode('utf-8') results in the corect data type, it is unnecessary for Python 3 (where strings are always unicode) and a meaningless operation for ciphertext.
    • If a given ciphertext has not a size, which is an exact multiple of the block size of the (symmetric) algorithm, it may be given in a special encoding (like base64) to avoid binary 0 characters or other stuff, which may be difficult to represent.