Mat0 Mat0 - 6 months ago 44
Swift Question

Best way to handle changing password when used for encrypt/decrypt

Problem:

I need to encrypt/decrypt a lot of data. This data is encrypted/decrypted using a password (more specifically using RNCrytor lib). One should be able to change this password.

My question is how this can be done most efficiently?

My not so great solution:

There must be a better method other than looping through all data and decrypting it. For then to encrypt it again using a new password.

Answer

This is one of the many problems that is solved by adding a layer of indirection. Generate a random key, use that key to encrypt the data, and store the key in a file (or database column or whatever) that is itself encrypted with a key derived from a password.

Something like (beware, I don't know Swift):

// Generation of the data keys
let dek = RNCryptor.randomDataOfLength(RNCryptor.FormatV3.keySize)
let dak = RNCryptor.randomDataOfLength(RNCryptor.FormatV3.keySize)

// Use these to work on the data
let encryptor = RNCryptor.EncryptorV3(encryptionKey: dek, hmacKey: dak)
let decryptor = RNCryptor.DecryptorV3(encryptionKey: dek, hmacKey: dak)

// Save the data keys encrypted with the password
let dek_file = RNCryptor.encryptData(dek, password: password)
let dak_file = RNCryptor.encryptData(dek, password: password)
// Store both dek_file and dak_file somewhere

// Next time, load dek_file and dak_file from where you stored them
let dek = RNCryptor.decryptData(dek_file, password: password)
let dak = RNCryptor.decryptData(dek_file, password: password)