2016-11-27 84 views
2

我想将二进制数据加密为二进制数据,然后以二进制数据解密。我如何在Python中做到这一点?我试图使用AES,但无法成功完成。将二进制数据加密为二进制数据并解密

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) 

回答

0

您可能正在寻找的是python中的xor位运算符。 基本上需要每对位的两个数和仅且仅当位中的一个是1返回1,否则返回0

Input = int(raw_input('Encrypt/Decrypt this >>>'), 2) #input must be in bit format 
key = 0b0100110 #'0b' indicates this is in second base 
Encryption = key^Input 
print Encryption 

以“1101001”作为输入的代码将打印79(该1001111)

重复同样的过程,像这样:

Decryption = key^Encryption 
print Decryption 

将打印105这是我们的原始输入(105 = 1101001)

FO [R更多的阅读,请访问:https://wiki.python.org/moin/BitwiseOperatorshttps://www.tutorialspoint.com/python/bitwise_operators_example.htm

0

我假设你正在使用PyCrypto,所以我建议考虑看看this blog post其中包括示例代码和引导您完成加密/解密的二进制文件的过程(不值得在这里复制代码)。

您可能还想看看simple-crypt,它摘录了一些使用PyCrypto的繁琐工作。

1

你没有指定,但你的代码看起来像你使用ECB模式。下面是一个简短的示例代码,我写了一个笑脸挑战,稍作修改以更好地适合您的示例代码。确保您的密钥长度为16个字节。另外,纯文本必须是16个字节的倍数。另一个挑战是你实现了一个填充函数。

需要注意的另一件事是,在加密数据后,最安全的方式是使用某种编码进行存储,通常使用Base64。然后,当你去解密它时,base64首先解码数据。

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))