PyCrypto problem using AES+CTR

后端 未结 5 1216
轮回少年
轮回少年 2020-12-03 14:37

I\'m writing a piece of code to encrypt a text using symmetric encryption. But it\'s not coming back with the right result...

from Crypto.Cipher import AES
i         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 15:25

    why does it need it to be 16 bytes when my key is 32 bytes

    It has to be the same length as the cipher's block size. CTR mode just encrypts the counter and XORs the plaintext with the encrypted counter block.

    Notes:

    1. the counter value MUST be unique -- if you EVER use the same counter value to encrypt two different plaintexts under the same key, you just gave away your key.
    2. like an IV, the counter is NOT secret -- just send it along with the ciphertext. If you make the code more complicated by trying to keep it secret, you will probably shoot yourself in the foot.
    3. the counter value need not be unpredictable -- starting with zero and adding one for each block is perfectly fine. But note that if you encrypt multiple messages, you need to keep track of the counter values that have already been consumed, i.e. you need to keep track of how many blocks have already been encrypted with that key (and you can't use the same key in different instances of your program or on different machines).
    4. the plain text can be any length -- CTR mode turns a block cipher into a stream cipher.

    Standard disclaimer: Crypto is hard. If you don't understand what you are doing, you will get it wrong.

    I just want to store some passwords across sessions.

    Use scrypt. scrypt includes encrypt and decrypt which use AES-CTR with a password-derived key.

    $ pip install scrypt
    
    $ python
    >>> import scrypt
    >>> import getpass
    >>> pw = getpass.getpass("enter password:")
    enter password:
    >>> encrypted = scrypt.encrypt("Guido is a space alien.",pw)
    >>> out = scrypt.decrypt(encrypted,pw)
    >>> out
    'Guido is a space alien.'
    

提交回复
热议问题