Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES Encrypt and Decrypt

I write an application by swift, i need AES Encrypt and Decrypt functionality, i received encrypted data from another .Net solution, but i can't find something to do it.

This is my .net Encryption:

 public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)     {         byte[] encryptedBytes = null;          byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };          using (MemoryStream ms = new MemoryStream())         {             using (RijndaelManaged AES = new RijndaelManaged())             {                 AES.KeySize = 256;                 AES.BlockSize = 128;                  var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);                 AES.Key = key.GetBytes(AES.KeySize / 8);                 AES.IV = key.GetBytes(AES.BlockSize / 8);                  AES.Mode = CipherMode.CBC;                  using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))                 {                     cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);                     cs.Close();                 }                 encryptedBytes = ms.ToArray();             }         }          return encryptedBytes;     } 

I need to decrypt function in swift.

like image 499
mehr Avatar asked Nov 21 '14 23:11

mehr


People also ask

Is AES encryption and decryption the same?

AES is a symmetric algorithm which uses the same 128, 192, or 256 bit key for both encryption and decryption (the security of an AES system increases exponentially with key length).

Is AES 256 Crackable?

AES 256 is virtually impenetrable using brute-force methods. While a 56-bit DES key can be cracked in less than a day, AES would take billions of years to break using current computing technology. Hackers would be foolish to even attempt this type of attack. Nevertheless, no encryption system is entirely secure.

How do I encrypt text in AES?

The Advanced Encryption Standard is the most commonly used encryption algorithm in use on computers and over the internet. To encrypt a string, select the green Encrypt button, enter the text you want to encrypt in the upper Plaintext box, and enter the key or password that it should be encrypted with in the Key box.


2 Answers

CryptoSwift Example

Updated to Swift 2

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

Usage:

let key = "bbC2H19lkVbQDfakxcrtNMQdd0FloLyw" // length == 32 let iv = "gqLOHUioQ0QjhuvI" // length == 16 let s = "string to encrypt" let enc = try! s.aesEncrypt(key, iv: iv) let dec = try! enc.aesDecrypt(key, iv: iv) print(s) // string to encrypt print("enc:\(enc)") // 2r0+KirTTegQfF4wI8rws0LuV8h82rHyyYz7xBpXIpM= print("dec:\(dec)") // string to encrypt print("\(s == dec)") // true 

Make sure you have the right length of iv (16) and key (32) then you won't hit "Block size and Initialization Vector must be the same length!" error.

like image 69
yutelin Avatar answered Sep 19 '22 02:09

yutelin


CryptoSwift Example

Updated SWIFT 4.*

func aesEncrypt() throws -> String {     let encrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).encrypt([UInt8](self.data(using: .utf8)!))     return Data(encrypted).base64EncodedString() }  func aesDecrypt() throws -> String {     guard let data = Data(base64Encoded: self) else { return "" }     let decrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).decrypt([UInt8](data))     return String(bytes: decrypted, encoding: .utf8) ?? self } 
like image 23
Yaroslav Dukal Avatar answered Sep 22 '22 02:09

Yaroslav Dukal