Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encrypt a binary data into binary and also decrypt [closed]

I want to encrypt a binary data into binary and then also decrypt in binary. How can I do this in python? I was trying to use AES but was unable to successfully do it.

 Key = '00000000’
 des = DES.new(key', DES.MODE_ECB)
 plain_text = "10101011"
 #encryption
 cipher_text = des.encrypt(plain_text)
 #decryption
 decrypted_pt = des.decrypt(cipher_text)
like image 907
Anjali Sharma Avatar asked Oct 23 '25 19:10

Anjali Sharma


1 Answers

You didn't specify, but your code makes it look like you're using ECB mode. Here's a short example of code I wrote for the cryptopals challenge, slightly modified to better fit your sample code. Make sure your key is 16 bytes long. Also, the plain text must be a multiple of 16 bytes. Another one of the challenges has you implementing a padding function.

Another thing to note is that after encrypting your data, the safest way to store that is in some sort of encoding, usually Base64 is used. Then when you go to decrypt it, you base64 decode the data first.

from Crypto.Cipher import AES
import base64


def ecb_encrypt(message, key):
    """ Encrypts a message in AES ECB mode with a given key
    ACCEPTS: Two strings, the plaintext message and the key
    RETURNS: A bytes string of base64 encoded ciphertext
    """

    aes = AES.new(key, AES.MODE_ECB)
    return base64.b64encode(aes.encrypt(message)).decode()


def ecb_decrypt(encrypted, key):
    """ Decrypts a ciphertext in AES ECB mode with a given key
    ACCEPTS: Two strings, the base64 encoded ciphertext and the key
    RETURNS: A bytes string of the plaintext message
    """

    aes = AES.new(key, AES.MODE_ECB)
    return aes.decrypt(base64.b64decode(encrypted))


if __name__ == "__main__":

    Key = "0000000000000000"
    plain_text = "1010101110101011"

    cipher_text = ecb_encrypt(plain_text, Key)
    decrypted_pt = ecb_decrypt(cipher_text, Key).decode()

    print("Original message: {}".format(plain_text))
    print("Encrypted message: {}".format(cipher_text))
    print("Decrypted message: {}".format(decrypted_pt))
like image 162
Andrew Lamarra Avatar answered Oct 26 '25 07:10

Andrew Lamarra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!