Quantcast
Channel: Swift - Encrypt and decrypt a string using a users password - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Swift - Encrypt and decrypt a string using a users password

$
0
0

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 as below

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

let decryptedMessage = decrypt(encryptedMessage, password)

Any advice would be much appreciated.

Thanks

UPDATE <-- Removed this section now

UPDATE 2

Ok I now have the following:

 func testEnc() throws {

    let ivKey = "tEi1H3E1aj26XNro"
    let message = "Test Message"
    let password = "pass123"

    let aesKey = password.padding(toLength: 32, withPad: "0", startingAt: 0)

    do {
        let messageArray = Array(message.utf8)
        let encrypted = try AES(key: aesKey, iv: ivKey, blockMode: .CBC, padding: .pkcs7).encrypt(messageArray)
        let encryptedString = String.init(bytes: encrypted, encoding: .utf8)
        let decrypted = try AES(key: aesKey, iv: ivKey, blockMode: .CBC, padding: .pkcs7).decrypt(encrypted)
        let decryptedString = String.init(bytes: decrypted, encoding: .utf8)
        assert(message == decryptedString)
    } catch {
        print(error)
    }
}

In the above code, the message is correctly encrypted and decrypted again.

decryptedString returns the same value as message which is perfect. However I need to store the encrypted value. In the above code encryptedString always returns nil. Does an AES encrypted Array<UInt8> not class as a byte string?


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images