Open chachapoly sealed box after removing and recreating a symmetric key (iOS)?

959 Views Asked by At

I am in a bit of a roadblock on my iOS app (first app for me), I want to encrypt data that I send to a server.

In order to do so I generate a symmetric key that I store in the keychain.

The key is generated in the following way:

SymmetricKey(data: password)

In this function the password is actually a computed SHA256 made like this: SHA256.hash(data: password) which gives me a digest and from that I extract the data representation to create my key.

Now when I encrypt data I do the following

    var encryptedData: Data = Data()
    if let key: SymmetricKey = try? readKey(account: encryptingKeyAccount){
        encryptedData = try! ChaChaPoly.seal(rawData, using: key).combined
    }
    return encryptedData

This returns me the data that I then send to the server.

In order to decrypt the data I do the following:

    var decryptedData: Data = Data()
    if let key: SymmetricKey = try? readKey(account: encryptingKeyAccount) {
        let sealedBox = try! ChaChaPoly.SealedBox(combined: encryptedData)
        decryptedData = try! ChaChaPoly.open(sealedBox, using: key)
    }
    return decryptedData

Now my problem is, if I logout (which means deleting the keys from the phone) and log back in (which in my mind recreates the same keys that were created before) then I am unable to decrypt my data... I have the following error when I try to open the box:

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: CryptoKit.CryptoKitError.authenticationFailure

Which I believe is due to how I create the key, which is not the same as the one that was deleted previously...

How can I fix this ?

Thanks !

0

There are 0 best solutions below