我写了一个
swift应用程序,我需要AES加密和解密功能,我从另一个.Net解决方案收到加密数据,但我找不到要做的事情.
这是我的.net加密:
@H_502_4@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,bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; }我需要在swift中解密功能.
解决方法
CryptoSwift
Example
更新到Swift 2
@H_502_4@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,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!) } }用法:
@H_502_4@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确保你有正确的长度iv(16)和键(32),那么你不会打“块大小和初始化矢量必须是相同的长度!错误.