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!)
}
}
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Jan 4, 2016

Awesome extension, very handy!

I was linked here through a SO question, for those having errors like:

"Block size and Initialization Vector must be the same length", or
"Unknown AES variant for given key."

It took me way longer than I'd admit to figure out so I thought I might save someone some time:

  1. The IV must be the same of block size, a constant defined in the code, which is 16B. That means your IV must be exactly 16 bytes/characters long.
  2. Using this extension, the key must be exactly 128, 192 or 256 bits long (16, 24 or 32 bytes/characters).
@thihaaung6245

This comment has been minimized.

Copy link

@thihaaung6245 thihaaung6245 commented Jan 25, 2016

was it AES-128?If its not can you fix it,please?

@pogland

This comment has been minimized.

Copy link

@pogland pogland commented Jan 31, 2016

How do you decrypt this in PHP?

@Foddy

This comment has been minimized.

Copy link

@Foddy Foddy commented Apr 22, 2016

How do you encrypt with PHP to be able to decrypt it in SWIFT?

@srinadhK

This comment has been minimized.

Copy link

@srinadhK srinadhK commented Nov 11, 2016

Here what we have to pass as input parameters for key and iv.

@imadeit

This comment has been minimized.

Copy link

@imadeit imadeit commented Dec 19, 2016

I tried to convert to Swift 3.0.2 as follows:
extension String {

func aesEncrypt(_ key: String, iv: String) throws -> String? {
    guard let data = self.data(using: String.Encoding.utf8) else {
        return nil
    }
    let enc = try AES(key: key, iv: iv, blockMode:.CBC).encrypt(data)
    let encData = Data(bytes: enc, count: Int(enc.count))
    let base64String: String = encData.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
    let result = String(base64String)
    return result
}

func aesDecrypt(_ key: String, iv: String) throws -> String? {
    guard let data = Data(base64Encoded: self, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }
    let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data)
    let decData = Data(bytes: dec, count: Int(dec.count))
    let result = NSString(data: decData, encoding: String.Encoding.utf8.rawValue)
    return String(result!)
}

}

Can you check the version above?

@yoonjason

This comment has been minimized.

Copy link

@yoonjason yoonjason commented May 19, 2017

How to use this code?
let data : String = blablabla
data = data.aesEncrypt(_ key: key, iv: iv)?
it?

@soumarsi

This comment has been minimized.

Copy link

@soumarsi soumarsi commented Aug 23, 2017

Hello,

When i import "CryptoSwift" to my class, error showing.
Which framework will added to my project when i import "CryptoSwift"?

@luhuiya

This comment has been minimized.

Copy link

@luhuiya luhuiya commented Jan 3, 2018

@sourmarsi you need to use pods and added this https://github.com/krzyzanowskim/CryptoSwift

@memolopezmx

This comment has been minimized.

Copy link

@memolopezmx memolopezmx commented Feb 9, 2018

@imadeit thank you =)

@memolopezmx

This comment has been minimized.

Copy link

@memolopezmx memolopezmx commented Feb 9, 2018

i get this error: Argument labels '(key:, iv:, blockMode:)' do not match any available overloads
in
let enc = try AES(key: key, iv: iv, blockMode:.CBC).encrypt(data)
=(

@DIntriglia

This comment has been minimized.

Copy link

@DIntriglia DIntriglia commented Feb 26, 2018

@ginppian
I'm no expert and am having many issues as well with this implementation, but the way to fix your line is this:
let enc = try AES(key: key, blockMode: .CBC(iv: iv)).encrypt(data)

@ashi5lab

This comment has been minimized.

Copy link

@ashi5lab ashi5lab commented May 7, 2018

I have an encrypted text which is encrypted using AES-128 (given by other person). I want to decrypt the same in Swift(for IOS). Anyone have any idea how to use this? I just have an encrypted text and a Password for the same.. Please help...

@smkdoss73

This comment has been minimized.

Copy link

@smkdoss73 smkdoss73 commented Aug 12, 2018

am also facing this error

Argument labels '(key:, iv:, blockMode:)' do not match any available overloads

 func aesDecrypt(key: String, iv: String) throws -> String {
        let data = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions(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!)
    }
@mavris

This comment has been minimized.

Copy link

@mavris mavris commented Apr 12, 2019

Did anyone found a solution for this error? Argument labels '(key:, iv:, blockMode:)' do not match any available overloads

@yassinemenssi

This comment has been minimized.

Copy link

@yassinemenssi yassinemenssi commented Mar 8, 2020

in swift 5 ???? not works

@christosNETinfo

This comment has been minimized.

Copy link

@christosNETinfo christosNETinfo commented May 27, 2020

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
}

@Shubh-viper

This comment has been minimized.

Copy link

@Shubh-viper Shubh-viper commented Jun 18, 2020

I have a bytearray. I want to encrypt it. can i use it instead of a string.

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