AES chiffrer et déchiffrer

J'écris une application par swift, j'ai besoin de la fonctionnalité AES Encrypt and Decrypt, j'ai reçu des données cryptées d'une autre solution .Net, mais je ne trouve pas quelque chose pour le faire.

Ceci est mon. Net Cryptage:

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; } 

J'ai besoin de décrypter la fonction dans Swift.

Exemple de CryptoSwift

Mis à jour à Swift 2

 import Foundation import CryptoSwift extension Ssortingng { func aesEncrypt(key: Ssortingng, iv: Ssortingng) throws -> Ssortingng{ let data = self.dataUsingEncoding(NSUTF8SsortingngEncoding) 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 base64Ssortingng: Ssortingng = encData.base64EncodedSsortingngWithOptions(NSDataBase64EncodingOptions(rawValue: 0)); let result = Ssortingng(base64Ssortingng) return result } func aesDecrypt(key: Ssortingng, iv: Ssortingng) throws -> Ssortingng { let data = NSData(base64EncodedSsortingng: 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 = NSSsortingng(data: decData, encoding: NSUTF8SsortingngEncoding) return Ssortingng(result!) } } 

Usage:

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

Assurez-vous que vous avez la bonne longueur de iv (16) et la key (32), alors vous ne bashez pas "Taille du bloc et l'initialisation du vector doit être la même longueur!" Erreur.

Exemple de CryptoSwift

Mis à jour à Swift 3

 func aesEncrypt(key: Ssortingng, iv: Ssortingng) throws -> Ssortingng { let data = self.data(using: .utf8)! let encrypted = try! AES(key: key.bytes, blockMode: .CBC(iv: iv.bytes), padding: .pkcs7).encrypt([UInt8](data)) let encryptedData = Data(encrypted) return encryptedData.base64EncodedSsortingng() } func aesDecrypt(key: Ssortingng, iv: Ssortingng) throws -> Ssortingng { let data = Data(base64Encoded: self)! let decrypted = try! AES(key: key.bytes, blockMode: .CBC(iv: iv.bytes), padding: .pkcs7).decrypt([UInt8](data)) let decryptedData = Data(decrypted) return Ssortingng(bytes: decryptedData.bytes, encoding: .utf8) ?? "Could not decrypt" } 

Il existe une bibliothèque Open Source "pure-swift" intéressante:

Exemple avec AES decrypt (obtenu à partir du file projet README.md):

 import CryptoSwift let setup = (key: keyData, iv: ivData) let decryptedAES = Cipher.AES(setup).decrypt(encryptedData) 

CryptoSwift est un projet très intéressant mais pour l'instant il a des limitations de vitesse AES. Soyez prudent si vous avez besoin de faire une cryptography sérieuse – il pourrait être utile de passer par la douleur du bridge implemmenting CommonCrypto.

BigUps à Marcin pour la mise en œuvre de pureSwift

J'utilisais CommonCrypto pour générer Hash à travers le code de MihaelIsaev / HMAC.swift de Facile à utiliser l'implémentation rapide de CommonCrypto HMAC . Cette implémentation est sans utiliser Bridging-Header, avec la création du file Module.

Maintenant, pour utiliser AESEncrypt et Decrypt, j'ai directement ajouté les fonctions dans "extension Ssortingng {" dans HAMC.swift.

 func aesEncrypt(key:Ssortingng, iv:Ssortingng, options:Int = kCCOptionPKCS7Padding) -> Ssortingng? { if let keyData = key.dataUsingEncoding(NSUTF8SsortingngEncoding), data = self.dataUsingEncoding(NSUTF8SsortingngEncoding), cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) { let keyLength = size_t(kCCKeySizeAES128) let operation: CCOperation = UInt32(kCCEncrypt) let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128) let options: CCOptions = UInt32(options) var numBytesEncrypted :size_t = 0 let cryptStatus = CCCrypt(operation, algoritm, options, keyData.bytes, keyLength, iv, data.bytes, data.length, cryptData.mutableBytes, cryptData.length, &numBytesEncrypted) if UInt32(cryptStatus) == UInt32(kCCSuccess) { cryptData.length = Int(numBytesEncrypted) let base64cryptSsortingng = cryptData.base64EncodedSsortingngWithOptions(.Encoding64CharacterLineLength) return base64cryptSsortingng } else { return nil } } return nil } func aesDecrypt(key:Ssortingng, iv:Ssortingng, options:Int = kCCOptionPKCS7Padding) -> Ssortingng? { if let keyData = key.dataUsingEncoding(NSUTF8SsortingngEncoding), data = NSData(base64EncodedSsortingng: self, options: .IgnoreUnknownCharacters), cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) { let keyLength = size_t(kCCKeySizeAES128) let operation: CCOperation = UInt32(kCCDecrypt) let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128) let options: CCOptions = UInt32(options) var numBytesEncrypted :size_t = 0 let cryptStatus = CCCrypt(operation, algoritm, options, keyData.bytes, keyLength, iv, data.bytes, data.length, cryptData.mutableBytes, cryptData.length, &numBytesEncrypted) if UInt32(cryptStatus) == UInt32(kCCSuccess) { cryptData.length = Int(numBytesEncrypted) let unencryptedMessage = Ssortingng(data: cryptData, encoding:NSUTF8SsortingngEncoding) return unencryptedMessage } else { return nil } } return nil } 

Les fonctions ont été sockets à partir de RNCryptor . C'était un ajout facile dans les fonctions de hachage et dans un seul file "HMAC.swift", sans utiliser l'en-tête Bridging. J'espère que cela sera utile pour les développeurs de swift nécessitant Hashing et AES Encryption / Decryption.

Exemple d'utilisation de l'AESDecrypt comme sous.

  let iv = "AA-salt-BBCCDD--" // should be of 16 characters. //here we are convert nsdata to Ssortingng let encryptedSsortingng = Ssortingng(data: dataFromURL, encoding: NSUTF8SsortingngEncoding) //now we are decrypting if let decryptedSsortingng = encryptedSsortingng?.aesDecrypt("12345678901234567890123456789012", iv: iv) // 32 char pass key { // Your decryptedSsortingng } 

Voici une bibliothèque utilisant la nouvelle API WebCrypto .

Pas d'en-tête de pont requirejs et c'est plus rapide que CryptoSwift.

https://github.com/etienne-martin/WebCrypto.swift

Cryptage basé sur un mot de passe

Chiffrement

 let crypto = WebCrypto() let input = Data("This is a ssortingng".utf8) let password = "password123" crypto.encrypt(data: input, password: password, callback: {(encrypted: Data?, error: Error?) in print(encrypted!) }) 

Déchiffrement

 crypto.decrypt(data: encrypted, password: password, callback: {(decrypted: Data?, error: Error?) in print(Ssortingng(data: decrypted!, encoding: .utf8)!) }) 

Chiffrement à base de key

Chiffrement

 let crypto = WebCrypto() let input = Data("This is a ssortingng".utf8) let key = "6f0f1c6f0e56afd327ff07b7b63a2d8ae91ab0a2f0c8cd6889c0fc1d624ac1b8" let iv = "92c9d2c07a9f2e0a0d20710270047ea2" crypto.encrypt(data: input, key: key, iv: iv, callback: {(encrypted: Data?, error: Error?) in print(encrypted!) }) 

Déchiffrement

 crypto.decrypt(data: encrypted, key: key, iv: iv, callback: {(encrypted: Data?, error: Error?) in print(Ssortingng(data: decrypted!, encoding: .utf8)!) }) 

Disclaimer: J'ai écrit cette bibliothèque.

Le code fourni par SHS ne fonctionnait pas pour moi, mais celui-ci l'a apparemment fait (j'ai utilisé un Bridging Header: #import <CommonCrypto/CommonCrypto.h> ):

 extension Ssortingng { func aesEncrypt(key:Ssortingng, iv:Ssortingng, options:Int = kCCOptionPKCS7Padding) -> Ssortingng? { if let keyData = key.data(using: Ssortingng.Encoding.utf8), let data = self.data(using: Ssortingng.Encoding.utf8), let cryptData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) { let keyLength = size_t(kCCKeySizeAES128) let operation: CCOperation = UInt32(kCCEncrypt) let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128) let options: CCOptions = UInt32(options) var numBytesEncrypted :size_t = 0 let cryptStatus = CCCrypt(operation, algoritm, options, (keyData as NSData).bytes, keyLength, iv, (data as NSData).bytes, data.count, cryptData.mutableBytes, cryptData.length, &numBytesEncrypted) if UInt32(cryptStatus) == UInt32(kCCSuccess) { cryptData.length = Int(numBytesEncrypted) let base64cryptSsortingng = cryptData.base64EncodedSsortingng(options: .lineLength64Characters) return base64cryptSsortingng } else { return nil } } return nil } func aesDecrypt(key:Ssortingng, iv:Ssortingng, options:Int = kCCOptionPKCS7Padding) -> Ssortingng? { if let keyData = key.data(using: Ssortingng.Encoding.utf8), let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters), let cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) { let keyLength = size_t(kCCKeySizeAES128) let operation: CCOperation = UInt32(kCCDecrypt) let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128) let options: CCOptions = UInt32(options) var numBytesEncrypted :size_t = 0 let cryptStatus = CCCrypt(operation, algoritm, options, (keyData as NSData).bytes, keyLength, iv, data.bytes, data.length, cryptData.mutableBytes, cryptData.length, &numBytesEncrypted) if UInt32(cryptStatus) == UInt32(kCCSuccess) { cryptData.length = Int(numBytesEncrypted) let unencryptedMessage = Ssortingng(data: cryptData as Data, encoding:Ssortingng.Encoding.utf8) return unencryptedMessage } else { return nil } } return nil } } 

De mon ViewController :

  let encoded = message.aesEncrypt(key: keySsortingng, iv: iv) let unencode = encoded?.aesDecrypt(key: keySsortingng, iv: iv) 

J'ai trouvé la solution, c'est une bonne bibliothèque.

Cryptage / déencryption AES de plate-forme 256 bits.

Ce projet contient l'implémentation du encryption AES 256 bits qui fonctionne sur toutes les plateforms (C #, iOS, Android). L'un des principaux objectives est de faire fonctionner AES sur toutes les plates-forms avec une implémentation simple.

Plateforms sockets en charge: iOS, Android, Windows (C #).

https://github.com/Pakhee/Cross-platform-AES-encryption