Can I decrypt a string encrypted using the pkcs11 AES 128-CTR library with the python Cryptodome module?

Question:

I want to decrypt binary what is encrypted by pkcs11 AES 128-CTR library.
Server gives me key, iv and data which is encrypted with pkcs11.
I don’t know the server encrypts data how.

from Cryptodome.Cipher import AES
from Cryptodome.Util import Counter

def AESDecrypt(_iv, key, enc_data):
    ctr = Counter.new(128, initial_value=int(binascii.hexlify(_iv), 16))
    cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
    raw_data = cipher.decrypt(enc_data)
    return raw_data

recv_data = b'x9ezxfaxf1x83xebxbexe9~x98xc79x81x96xd1x14'
recv_iv = b'x2fxe2xb3x33xcexdax8fx98xf4xa9x9bx40xd2xcdx34xa8'
recv_key = b'x1fx8ex49x73x95x3fx3fxb0xbdx6bx16x66x2ex9ax3cx17'

"""send message: abcd"""

But, I can’t decrypt data string.
Isn’t the above code compatible with the pkcs11 library?
If so, how can i decrypt that data string?

Asked By: Zaregon

||

Answers:

Below is an example AES128-CTR decryption based on the PyCryptodome’s documentation:

from Crypto.Cipher import AES
from Crypto.Util import Counter

def AESDecrypt(_iv, key, enc_data):
    # Assuming 64-bit nonce and 64-bit counter
    noncepart=_iv[:8]
    counterpart=_iv[8:]
    print('Key: ' + key.hex())
    print('IV: ' + _iv.hex())
    print('IV(nonce): ' + noncepart.hex())
    print('IV(counter): ' + counterpart.hex())
    print('Ciphertext: ' + enc_data.hex())
    cipher = AES.new(key, AES.MODE_CTR, nonce=noncepart,initial_value=counterpart)
    raw_data = cipher.decrypt(enc_data)
    print('Plaintext: ' + raw_data.hex())
    return raw_data

print('nFor data in question:')
AESDecrypt(
    b'x2fxe2xb3x33xcexdax8fx98xf4xa9x9bx40xd2xcdx34xa8',
    b'x1fx8ex49x73x95x3fx3fxb0xbdx6bx16x66x2ex9ax3cx17', 
    b'x9ezxfaxf1x83xebxbexe9~x98xc79x81x96xd1x14'
    )

print('nFor official test vector:')
AESDecrypt(
    # NIST SP 800-38A, section F.5.2, block 1
    b'xf0xf1xf2xf3xf4xf5xf6xf7xf8xf9xfaxfbxfcxfdxfexff', 
    b'x2bx7ex15x16x28xaexd2xa6xabxf7x15x88x09xcfx4fx3c', 
    b'x87x4dx61x91xb6x20xe3x26x1bxefx68x64x99x0dxb6xce'
    ) # -> gives 6bc1bee22e409f96e93d7e117393172a

Your data decrypts to: 7e3099d22395525fc49021c34d356c44.

As CTR mode is basically a stream cipher an encryption of "abcd" should be four bytes long and not 16 bytes (AES block size). Are you sure that CTR mode is used?

Good luck with your project!

Answered By: vlp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.