Created
July 31, 2018 23:02
-
-
Save cscouto/73234812431194daab920d96434bb63d to your computer and use it in GitHub Desktop.
SWIFT - Encrypt/Decrypt AES with CryptoSwift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// String+AES.swift | |
// bitcoin | |
// | |
// Created by Tiago Do Couto on 7/31/18. | |
// Copyright © 2018 coutocode. All rights reserved. | |
// | |
import CryptoSwift | |
extension String { | |
func aesEncrypt(key: String, iv: String) throws -> String{ | |
let data = self.data(using: String.Encoding.utf8) | |
let bytes = [UInt8](data!) | |
let enc = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).encrypt(bytes) | |
let encData = NSData(bytes: enc, length: Int(enc.count)) | |
let base64String: String = encData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)); | |
let result = String(base64String) | |
return result | |
} | |
func aesDecrypt(key: String, iv: String) throws -> String { | |
let data = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions(rawValue: 0)) | |
let bytes = [UInt8](data! as Data) | |
let dec = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).decrypt(bytes) | |
let decData = NSData(bytes: dec, length: Int(dec.count)) | |
let result = NSString(data: decData as Data, encoding: String.Encoding.utf8.rawValue) | |
return String(result!) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment