Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
String+AES.swift
import Foundation
import CryptoSwift
extension String {
func aesEncrypt(key: String, iv: String) throws -> String{
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
let enc = try 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 aesDecrypt(key: String, iv: String) throws -> String {
let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data!.arrayOfBytes(), padding: PKCS7())
let decData = NSData(bytes: dec, length: Int(dec.count))
let result = NSString(data: decData, encoding: NSUTF8StringEncoding)
return String(result!)
}
}
@seonar22
Copy link

seonar22 commented Nov 4, 2021

Swift 5.2

func cryptoSwiftAESEncrypt(key: String, iv: String ) -> String? {
        guard let dec = try? AES(key: key, iv: iv, padding: .pkcs7).encrypt(Array(self.utf8)) else {   return nil }
        let decData = Data(bytes: dec, count: Int(dec.count)).base64EncodedString(options: .lineLength64Characters)
        return decData
}
func cryptoSwiftAESDecrypt(key: String, iv: String) -> String? {
      guard let dec = try? AES(key: key, iv: iv, padding: .pkcs7).decrypt(Array(self.utf8)) else {    return nil    }
      let decData = Data(bytes: dec, count: Int(dec.count)).base64EncodedString(options: .lineLength64Characters)
      return decData
}

cryptoSwiftAESDecrypt is not working and show some error related to DataPadding or Vector. I forgot original error after editing the method, but the encrypted String is base64 encoded, so I decoded it into Data first, before passing as byte array to decrypt.

Feel free to correct me. I am posting this just in case someone has similar error.

func cryptoSwiftAESDecrypt(key: String, iv: String) -> String? {
        guard let data = Data(base64Encoded: self),
              let dec = try? AES(key: key, iv: iv, padding: .pkcs7).decrypt(data.bytes) else { return nil }
        
        let decData = Data(bytes: dec, count: Int(dec.count))
        
        return String(data: decData, encoding: .utf8)
}

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