iosobjective-cencryptionpublic-key-encryptionaescryptoserviceprovider

Generating secret key for AES 256 Encryption from Keychain


I am working on a project where I need to encrypt/decrypt some data locally. I am using RNCryptor for the encryption and decryption process. To do that I need to use key, i don't want to define that key from app side like:

NSString *password = @"Secret password";

Is there any way to define the key using any property from keychain so that I can use the same key without defining it in code base.


Solution

  • If you do not want to declare a static key or derive a key from the static password, you can certainly derive a random key and store that value in the Keychain. SecRandomCopyBytes will return an array of arbitrary length that was generated in a cryptographically secure manner. You can request 32 bytes (256 bits) from this service and store that as your key in the keychain. Obviously be aware that if you call this multiple times it will not return the same result, so you must not lose the key once you have stored it.