11

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

4
  • Potentially relevant reading: stackoverflow.com/questions/27072021/aes-encrypt-and-decrypt Commented Sep 28, 2017 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? Commented Sep 28, 2017 at 23:10
  • security.stackexchange.com/questions/38828/… Commented Sep 28, 2017 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. github.com/RNCryptor/RNCryptor Commented Sep 29, 2017 at 0:03

2 Answers 2

22

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 encrypt 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 to use as the encryption key for my user data. I then encrypted that 32 character string 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.

Sign up to request clarification or add additional context in comments.

23 Comments

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, 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.
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 github.com/RNCryptor/RNCryptor-Spec/blob/master/… for a description of the process.
@MatthewCawley, also consider the case where multiple users share the same password.
@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).
|
3

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.

3 Comments

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
"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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.