Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP compatible AES Encryption and Decryption with Swift and CryptoSwift
// Credit should be given to;
// https://gist.github.com/yutelin/f4f66e0c78474db1de51#file-string-aes-swift
// https://gist.github.com/bradbernard/2a7af4c2200cb3794768#file-swift-encryption
// And most importantly to https://github.com/krzyzanowskim/CryptoSwift
import Foundation
import CryptoSwift
extension String {
func aesEncryptWithStaticIV(key: String, iv: String) -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
let enc = AES(key: key, iv: iv, blockMode:.CBC)?.encrypt(data!.arrayOfBytes(), padding: PKCS7())
let encData = NSData(bytes: enc!, length: Int(enc!.count))
let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let result = String(base64String)
return result
}
func aesDecryptWithStaticIV(key: String, iv: String) -> String {
let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
let dec = AES(key: key, iv: iv, blockMode:.CBC)?.decrypt(data!.arrayOfBytes(), padding: PKCS7())
let decData = NSData(bytes: dec!, length: Int(dec!.count))
var result = NSString(data: decData, encoding: NSUTF8StringEncoding)
return String(result!)
}
func aesEncryptWithoutPaddingWithStaticIV(key: String, iv: String) -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
let enc = AES(key: key, iv: iv, blockMode:.CBC)?.encrypt(data!.arrayOfBytes())
let encData = NSData(bytes: enc!, length: Int(enc!.count))
let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let result = String(base64String)
return result
}
func aesDecryptWithoutPaddingWithStaticIV(key: String, iv: String) -> String {
let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
let dec = AES(key: key, iv: iv, blockMode:.CBC)?.decrypt(data!.arrayOfBytes())
let decData = NSData(bytes: dec!, length: Int(dec!.count))
var result = NSString(data: decData, encoding: NSUTF8StringEncoding)
return String(result!)
}
func aesEncrypt(key: String) -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let keyData = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!.arrayOfBytes()
let ivData = Cipher.randomIV(keyData.count)
let encrypted = Cipher.AES(key: keyData, iv: ivData, blockMode:.CBC).encrypt(data!.arrayOfBytes())
let encryptedData = NSData(bytes: encrypted!, length: Int(encrypted!.count))
let sendData = NSMutableData(bytes: ivData, length: Int(ivData.count))
sendData.appendData(encryptedData)
let base64String: String = sendData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let result = String(base64String)
return result
}
func aesDecrypt(key: String) -> String {
let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
let keyData = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!.arrayOfBytes()
let ivData = data!.subdataWithRange(NSRange(location: 0, length: AES.blockSize)).arrayOfBytes()
let encryptedData = data!.subdataWithRange(NSRange(location: AES.blockSize, length: (data!.length - AES.blockSize) as Int))
let decrypted = Cipher.AES(key: keyData, iv: ivData, blockMode:.CBC).decrypt(encryptedData.arrayOfBytes())
let decryptedData = NSData(bytes: decrypted!, length: Int(decrypted!.count))
let decryptedString = NSString(data: decryptedData, encoding: NSUTF8StringEncoding)!
return String(decryptedString)
}
}
@cloyOnGit

This comment has been minimized.

Copy link

cloyOnGit commented Oct 26, 2015

Hey tlarevo,

Thank you for the code.
this is my string "secret"
after encryption of the above string i got the following encrypted string "64c2VjcmV0"

but when i tried to decrypt by the following code i got the following error
nil
fatal error: unexpectedly found nil while unwrapping an Optional value

let key: [UInt8] = self.generateArray("secret0key000000") //16
let iv: [UInt8] = self.generateArray("0000000000000000") //16
let input: String = "64c2VjcmV0"

let data = NSData(base64EncodedString: input, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
print(data)
do{
let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data!.arrayOfBytes())
let decData = NSData(bytes: dec, length: Int(dec.count))
var result = NSString(data: decData, encoding: NSUTF8StringEncoding)
print(result!)
}catch{

}

@tnavadiya

This comment has been minimized.

Copy link

tnavadiya commented Mar 5, 2016

Hi,

    let decrypted = Cipher.AES(key: keyData, iv: ivData, blockMode:.CBC).decrypt(encryptedData.arrayOfBytes())

This line give an error as below:

type 'Cipher' has no member 'AES' in function -> func aesDecrypt(key: String

@boardmain

This comment has been minimized.

Copy link

boardmain commented Mar 10, 2016

same error type 'Cipher' has no member 'AES' in function -> func aesDecrypt(key: String

@dantarakan

This comment has been minimized.

Copy link

dantarakan commented May 18, 2016

@boardmain, @tnavadiya, to fix this error you should replace these two lines:

let ivData = Cipher.randomIV(keyData.count)
let encrypted = Cipher.AES(key: keyData, iv: ivData, blockMode:.CBC).encrypt(data!.arrayOfBytes())

by these:

let ivData = AES.randomIV(keyData.count)
let encrypted = AES(key: keyData, iv: ivData, blockMode:.CBC).encrypt(data!.arrayOfBytes())

Cheers!

@sicaboy

This comment has been minimized.

Copy link

sicaboy commented Jan 3, 2017

Could anyone modify this file to adapt swift 3? thx

@k41ed

This comment has been minimized.

Copy link

k41ed commented Jan 11, 2017

can you give me an example of file encryption and decryption with swift 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment