ios – AES加密和解密

ios – AES加密和解密,第1张

概述我写了一个 swift应用程序,我需要AES加密解密功能,我从另一个.Net解决方案收到加密数据,但我找不到要做的事情. 这是我的.net加密: public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; 我写了一个 swift应用程序,我需要AES加密和解密功能,我从另一个.Net解决方案收到加密数据,但我找不到要做的事情.

这是我的.net加密:

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

import Foundationimport CryptoSwiftextension 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!)    }}

用法:

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

确保你有正确的长度iv(16)和键(32),那么你不会打“块大小和初始化矢量必须是相同的长度!错误.

总结

以上是内存溢出为你收集整理的ios – AES加密和解密全部内容,希望文章能够帮你解决ios – AES加密和解密所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1111441.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存