Search code examples
pythonpython-3.xencryptionpassword-encryption

Can I use the AES I.V. or nonce as a Password Salt?


I'm trying to make a Python program which will take the file and key and then it will encrypt the file. I already know that the AES-GCM and AES-CFB mode uses a nonce and IV, respectively. And I currently store the IV/nonce in the encrypted file itself. I'm pondering over the idea if I can use the IV/nonce of the AES-CFB/AES-GCM as my password hashing salt?

Earlier I hashed the key provided, but when I came to know about Rainbow-tables, I thought of using a more sophisticated way. The approach I came to know about was PBKDF2.

if filepath.endswith(EXT):
      method = 'decrypt'
      flag = False
      with open(filepath, 'rb+') as f:
        f.seek(-NONCE_SIZE,2)
        iv = f.read()
      os.truncate(filepath, os.path.getsize(filepath) - NONCE_SIZE)

    # If the file doesn't end with the required extension,
    # then identify the method as `encrypt` and do the same
    # with the key provided.
    else:
      method = 'encrypt'
      flag = True
      iv = Random.new().read(NONCE_SIZE)

    # Make a cipher object with the nonce and key and write
    # to the file with the arguments.
    # Previous approach as commented-out code line below
    # key = hashlib.sha3_256(key.encode()).digest()
    key = PBKDF2(key, iv, dkLen=32)
    crp = getattr(AES.new(key, AES.MODE_GCM, nonce=iv), method)

I expect that the IV/nonce used as a password hashing salt provides the security required.


Solution

  • That is what the IV and the nonce are there for already. Using them twice might have catastrophic effects on the encryption. A nonce is by definition a number that is used only once.