10

I'm trying to encrypt a String using a password in Swift but not sure how to do it. I need something that works like this

let password = "password"
let message = "messageToEncrypt"
let encryptedMessage = encrypt(message, password)
...

let decryptedMessage = decrypt(encryptedMessage, password)

Any advice would be much appreciated.

Thanks

UPDATE

Based on the idea below i have the following method

func testEnc() throws {
    
    let ivKey = "tEi1H3E1aj26XNro"
    let message = "Test Message"
    let password = "pass123"
    
    let aesKey = password.padding(toLength: 32, withPad: "0", startingAt: 0)
    
    let aes = try AES(key: aesKey, iv: ivKey)
    let cipherBytes: Array<UInt8> = try aes.encrypt(Array(message.utf8))
    
    let cipherData = NSData(bytes: cipherBytes, length: Int(cipherBytes.count))
    let cipherString = cipherData.base64EncodedString(options: .lineLength64Characters)
    //cipherString => beQ7u8hBGdFYqNP5z4gBGg==
    let decryptedCipherBytes = try aes.decrypt(Array(cipherString.utf8))
    let decryptedCipherData = NSData(bytes: decryptedCipherBytes, length: Int(cipherBytes.count))
    let decryptedCipherString = decryptedCipherData.base64EncodedString(options: .lineLength64Characters)
    
    assert(message == decryptedCipherString)
}

at the line

    let decryptedCipherBytes = try aes.decrypt(Array(cipherString.utf8))

I am getting the following error:

[CryptoSwift.AES.Error: dataPaddingRequired]
Conform 'CryptoSwift.AES.Error' to Debugging.Debuggable to provide more debug information.

Do you have any idea why it would not be able to decrypt the data that it has just encrypted?

Thanks

Matthew Cawley
  • 2,828
  • 1
  • 31
  • 42
  • Potentially relevant reading: https://stackoverflow.com/questions/27072021/aes-encrypt-and-decrypt – CollinD Sep 28 '17 at 23:05
  • I have already read that post but that is based on a key based encryption using key and iv. I need a password based method. If that is the way to go. How would I generate a key and iv given only a password? – Matthew Cawley Sep 28 '17 at 23:10
  • https://security.stackexchange.com/questions/38828/how-can-i-securely-convert-a-string-password-to-a-key-used-in-aes – CollinD Sep 28 '17 at 23:11
  • 2
    There is no standard for what it means "to encrypt." It highly depends on what you're trying to do and whether you need to be compatible with some other piece of software. Is your code the only code that will need to decrypt this? Take a look at RNCryptor for an encryption format that works the way you're describing. https://github.com/RNCryptor/RNCryptor – Rob Napier Sep 29 '17 at 00:03

2 Answers2

19

Please see updated section below striked out section. I have left the striked out section to give context to the comments and to show how not to do for security purposes

I have worked it out using CryptoSwift

func testEnc() throws {

    //has to be 16 characters
    //ivKey is only hardcoded for use of this example
    let ivKey = "tEi1H3E1aj26XNro"
    let message = "Test Message"
    let password = "pass123"

    //key has to be 32 characters so we pad the password
    let aesKey = password.padding(toLength: 32, withPad: "0", startingAt: 0)

    let encrypted = try message.encryptToBase64(cipher: AES(key: aesKey, iv: ivKey, blockMode: .CBC, padding: .pkcs7))
    //returns: beQ7u8hBGdFYqNP5z4gBGg==

    let decrypted = try encrypted?.decryptBase64ToString(cipher: AES(key: aesKey, iv: ivKey, blockMode: .CBC, padding: .pkcs7))
    //returns: Test Message
    assert(message == decrypted)

}

UPDATE

The above methodology, while it will work, is insecure; please read comments on this answer for more information

Based on the comments and feedback, I have written a new example that uses the framework RNCryptor

To encryp and decrypt messages I use the following 2 methods.

    func encryptMessage(message: String, encryptionKey: String) throws -> String {
        let messageData = message.data(using: .utf8)!
        let cipherData = RNCryptor.encrypt(data: messageData, withPassword: encryptionKey)
        return cipherData.base64EncodedString()
    }

    func decryptMessage(encryptedMessage: String, encryptionKey: String) throws -> String {

        let encryptedData = Data.init(base64Encoded: encryptedMessage)!
        let decryptedData = try RNCryptor.decrypt(data: encryptedData, withPassword: encryptionKey)
        let decryptedString = String(data: decryptedData, encoding: .utf8)!

        return decryptedString
    }

In my use case I needed to be able to handle encryption and decryption based off a password that could be changed without having to re-encrypt everything.

What I did is generated a random 32 character string and encrypted that with the password. If the user changes their password, they simply decrypt the key with the old password and re-encrypt it with the new password. This ensure that all existing content can be decrypted while still being secured by the user's password.

To generate the encryption key is use the following method:

func generateEncryptionKey(withPassword password:String) throws -> String {
    let randomData = RNCryptor.randomData(ofLength: 32)
    let cipherData = RNCryptor.encrypt(data: randomData, withPassword: password)
    return cipherData.base64EncodedString()
}

Note: You would only generate this encryption key for the user once as it would then be stored somewhere where the user can return it using their password.

Matthew Cawley
  • 2,828
  • 1
  • 31
  • 42
  • 1
    Note that this is incredibly insecure. You've thrown away the vast majority of the AES keyspace. Human-typable passwords are not the same thing as keys. You have to stretch passwords into keys using a KDF (typically PBKDF2, which is available in CryptoSwift). That will require generating a random salt that you will need to store with the encrypted data. This is also very insecure because you have a fixed IV. IVs can't be hard-coded like this. You need to generate a random one and pass it along with the encrypted data. – Rob Napier Sep 29 '17 at 01:24
  • Rob, can you give an example of how you can have a string that is encrypted by a user's password and decrypted using the same password? You make some valid points, but without any examples to show me the correct way of doing things, it is hard to make the adjustments. The use case of my code will be encrypt a private key so that it can be stored in a database. The private key will be paired with a public key to handle the main encryption. The private key needs to be encrypted with the user's password and decryptable using the user's password and noone else. – Matthew Cawley Sep 29 '17 at 01:31
  • Just to add, the IV will not be hard coded like it is above. I will use something such as a md5 of the user's password or some other one way encryption. – Matthew Cawley Sep 29 '17 at 01:32
  • I think using a IV generated via one way encryption would be more secure that a randomly generate IV that I have to save somewhere. – Matthew Cawley Sep 29 '17 at 01:34
  • That's completely backwards. Hashing the password to generate the IV is exactly as insecure as a hardcoded IV. You must never encrypt two messages with the same Key+IV combination, and you would always do that here. – Rob Napier Sep 29 '17 at 01:36
  • 2
    I agree that building this well is very difficult. That's why I pointed you to RNCryptor, which does all of this for you. See https://github.com/RNCryptor/RNCryptor-Spec/blob/master/RNCryptor-Spec-v3.md for a description of the process. – Rob Napier Sep 29 '17 at 01:37
  • How do you suggest randomly generating an IV that has to be kept secure while still passing it around in the encrypted data. In order to decrypt the data, the IV must be readable. Therefore having it with the encrypted data makes it readily available to anyone with that data. Encryption is a mind blowing thing haha – Matthew Cawley Sep 29 '17 at 01:38
  • The IV is not a secret. It is public information. You pass it around as plaintext. – Rob Napier Sep 29 '17 at 01:39
  • This just confuses the hell out of me haha – Matthew Cawley Sep 29 '17 at 01:39
  • How is that more secure than an IV generated from the user's password? – Matthew Cawley Sep 29 '17 at 01:40
  • Understandable. Which is why I recommend to folks that they do not try to create their own encryption data formats. It's very hard and there are many subtle ways to do it wrong that look ok." – Rob Napier Sep 29 '17 at 01:40
  • If you generate the IV from the user's password and also generate the key from the user's password, then every message you encrypt with that key will have the same Key+IV pair. You should never repeat a Key+IV pair in CBC mode AES. It doesn't matter that people know what the IV is. What matters is that a particular Key+IV should never be used for two messages. – Rob Napier Sep 29 '17 at 01:41
  • I have just read this: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Initialization_vector_.28IV.29 which explains this in a bit more of a dummed down version :) Thank you for pointing this out to me. I will change over to RNCryptor :) – Matthew Cawley Sep 29 '17 at 01:42
  • Best of luck on it! – Rob Napier Sep 29 '17 at 01:43
  • I think what made it a bit harder for me to understand for my case, is that the key+iv combo will never be used to encrypt more than one message. It will only ever be used for one message. – Matthew Cawley Sep 29 '17 at 01:43
  • 2
    @MatthewCawley, also consider the case where multiple users share the same password. – zneak Sep 29 '17 at 01:44
  • There's a bug in decryptMessage. It should not base64 encode the string before returning it, instead it needs to convert the data to a string `decryptedString = String(data: decryptedData, encoding: .utf8)!`. Otherwise this was super helpful, thanks! – ToddH Nov 08 '17 at 00:14
  • @RobNapier - It has only just clicked that you are the Creator of RNCryptor :D Well played and great job on the framework :) – Matthew Cawley Jan 04 '18 at 20:22
  • @MatthewCawley I like your solution very much and it helped me a lot. Could you please share what is your solution here if a user forgets the password? Thanks! – lajosdeme Mar 13 '19 at 18:24
  • 1
    @lajosdeme - There are a couple of options for a forgotten password. One would be a backup key. When you encrypt your key with the password you generate a second random string and also encrypt the key using that random string. The user is responsible for keeping that backup key safe. Alternatively, you could have the server keep a second decryption key in an encrypted location requiring manual intervention to reset a password (i.e., user requests a password reset, you decrypt the backup key and send it to the user, who can then use that key to reset their password). – Matthew Cawley Mar 15 '19 at 18:38
2

One of the most popular libraries out there is CryptoSwift (more than 4000 stars!). It provides a lot of crypto related functionality that might interest you.

For your question, I am assuming you want to do AES based encryption, and the message is small (but further down, there is a example for larger files etc.). Using the library mentioned above, the code (taken from the library's page itself--please scroll down):

do {
    let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap") 
    let ciphertext = try aes.encrypt(Array("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8))
} catch { }

One of the questions asked is how to get IV (Initialization Vector). In this example, the IV is simply the reverse of the password, which may not be a good idea in real world applications. The going principle is that the IV doesn't need to be secret. It just needs to be random, and if possible, unique. So, you can save the IV with the file, in a database with the cipher text.

mgeek
  • 21
  • 3
  • I'm trying this but I am getting the following error `Block size and Initialization Vector must be the same length!` I am generating my IV by reversing the password – Matthew Cawley Sep 28 '17 at 23:50
  • "which may not be a good idea in real world applications." It is both a very bad idea and does not work unless the password is precisely one block in length. Also a password is not the same thing a key. Passing a human-typable password as an AES key is incredibly insecure (it destroys most of the benefit of AES's key size). While CryptoSwift is a nice package, it is a very low-level package. It assumes you have a strong background in order to correctly use crypto primitives, and will happily allow you to build things that are highly insecure. – Rob Napier Sep 29 '17 at 00:00
  • I am not sure why you are getting the error. I just tried this and it seems to be working. Can you post your code. (Sorry...newbee here on stackoverflow, so don't know all the bells and whistles). @RobNapier I completely agree. But I was trying to be as simple as possible, not suggesting that this is how you _should_ do it. Key based encryption is tough--Salting, creating a (truly unique) crypto-random IV, etc is equally important. I completely agree with you there. – mgeek Sep 29 '17 at 00:27