Search code examples
pythonpycrypto

Storing and reading encrypted strings from file in Python


I'm using AES (from PyCrypto) to encrypt passwords and store it in a file. The format of the file is:

user:username
key:<encrypted key>

And this is the method I used for encryption:

BLOCK_SIZE = ..
PADDING = ..
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
cipher = AES.new("abcdefgh12345678")

encrypted_key = EncodeAES(cipher, 'ABC123')

Now, how do I read the key from the file for decrypting it? If I use line.split(":"), wouldn't it cause problem if the encrypted key itself had ":" as a character?

Is there any way to avoid ":" while encrypting it? Or is there a better way for storing the keys? I cannot use hashing as I need the key for some other functionality. Thanks.


Solution

  • Now, how do I read the key from the file for decrypting it? If I use line.split(":"), wouldn't it cause problem if the encrypted key itself had ":" as a character?

    Of course it would—that's why exactly split has a second, optional argument max_split:

    key, value = line.split(':', 1)
    

    Alternatively, you can use partition:

    key, _, value = line.partition(':')
    

    The difference between the two is what happens when there isn't a colon at all; the former will return one element, giving you a ValueError from trying to unpack it into two variables, while the latter will just give you an empty value.


    However, it's worth noting that if you're using Base 64, : is never going to appear in the first place. The only character used by Base 64 are A-Z, a-z, 0-9, +, and /. There are some Base 64 variants, and maybe one of them does use :, but the standard version, as applied by Python's base64 module, does not.