2016-11-27 538 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))