-1

I'm new on python. I'm working on this code about file encryption with AES

https://stackoverflow.com/a/20868265/2955896

it uses this key for encryption

key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'

How can I generate the key randomly in order to make decryption not possible?

mehmet
  • 491
  • 1
  • 5
  • 4
  • Err... I take it you want a random key that you can use - not quite sure what the purpose of *in order to make decryption not possible?* is... – Jon Clements Mar 29 '15 at 10:35
  • Only one time pad can make decryption impossible without knowing the key, but good cryptography algorithms can make decryption very difficult. – user4098326 Mar 29 '15 at 10:46

1 Answers1

0

The most practical way is to read random data from whichever random device your operating system supplies. This is conveniently accessed by using os.random();

In [1]: import os

In [2]: os.urandom(128)[:10]
Out[2]: b'\xee&\x06s?\x8d\xfcI=\x07'

(Only showing the first 10 bytes for convenience.)

This will return different data every time you call it;

In [3]: os.urandom(128)[:10]
Out[3]: b')\x12TQ\xf5\xa3G\xe2\xb00'

In [4]: os.urandom(128)[:10]
Out[4]: b'\xce\xba\xd2Gr\x8c6\xba\xb7\x91'

In [5]: os.urandom(128)[:10]
Out[5]: b'~\x00\xca\x0c=\xd3\xff\xef\xc8\x14'

In [6]: os.urandom(128)[:10]
Out[6]: b'\xb0~vb"\xd6(F\xb7v'

Edit:

From Python 3.6 onwards you should use the secrets module for cryptograhically strong random numbers. For example:

In [1]: import secrets

In [2]: secrets.token_urlsafe(32)
Out[2]: 'SgkZmSckZcSB3a4uK-SFPN6vevgx231sHs-aE5GlP-g'

As of 2015, 32 is the default number of bytes requested;

In [3]: secrets.token_urlsafe()
Out[3]: 'qbmwK_2-_f6UQOTLJcweYcwZQze8lo3dtIuEKWhpb_w'
Roland Smith
  • 42,427
  • 3
  • 64
  • 94