Last active
January 22, 2024 12:36
-
-
Save yutelin/f4f66e0c78474db1de51 to your computer and use it in GitHub Desktop.
String+AES.swift
This file contains hidden or 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
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 How do Decrypt without IV? because i don't have IV.
I just have a string and KEY for decryption.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.