我有一个应用程序,该应用程序必须发送先由MD5然后由3DES加密的登录凭据。
我设法使用CryptoSwift通过MD5加密字符串。但是我找不到任何可以在Swift上通过3DES加密的东西。
我已经尝试过CommonCrypto。据我所知,这是用C语言编写的,但可以通过桥接头导入到目标C语言中。
我发现了一些文章和教程,它们告诉我如何通过桥接标头(警告它不适用于框架)或Model.map将CommonCrypto导入Swift。但是,两者都不起作用。我不确定这是否是最新版本的iOS或Xcode中的限制。
有人可以建议替代方法吗?
谢谢
已编辑
嗨,请参阅我已采取的以下步骤
事实证明,我完全把这个复杂化了。
我不需要导入任何外部库或SDK,我只需要一个桥接头文件即可 #import <CommonCrypto/CommonCrypto.h>
#import <CommonCrypto/CommonCrypto.h>
override func viewDidLoad() { super.viewDidLoad() myEncrypt("my string to encrypt") } func myEncrypt(encryptData:String) -> NSData?{ var myKeyData : NSData = ("myEncryptionKey" as NSString).dataUsingEncoding(NSUTF8StringEncoding)! var myRawData : NSData = encryptData.dataUsingEncoding(NSUTF8StringEncoding)! var iv : [UInt8] = [56, 101, 63, 23, 96, 182, 209, 205] // I didn't use var buffer_size : size_t = myRawData.length + kCCBlockSize3DES var buffer = UnsafeMutablePointer<NSData>.alloc(buffer_size) var num_bytes_encrypted : size_t = 0 let operation: CCOperation = UInt32(kCCEncrypt) let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES) let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding) let keyLength = size_t(kCCKeySize3DES) var Crypto_status: CCCryptorStatus = CCCrypt(operation, algoritm, options, myKeyData.bytes, keyLength, nil, myRawData.bytes, myRawData.length, buffer, buffer_size, &num_bytes_encrypted) if UInt32(Crypto_status) == UInt32(kCCSuccess){ var myResult: NSData = NSData(bytes: buffer, length: num_bytes_encrypted) free(buffer) println("my result \(myResult)") //This just prints the data let keyData: NSData = myResult let hexString = keyData.toHexString() println("hex result \(hexString)") // I needed a hex string output myDecrypt(myResult) // sent straight to the decryption function to test the data output is the same return myResult }else{ free(buffer) return nil } } func myDecrypt(decryptData : NSData) -> NSData?{ var mydata_len : Int = decryptData.length var keyData : NSData = ("myEncryptionKey" as NSString).dataUsingEncoding(NSUTF8StringEncoding)! var buffer_size : size_t = mydata_len+kCCBlockSizeAES128 var buffer = UnsafeMutablePointer<NSData>.alloc(buffer_size) var num_bytes_encrypted : size_t = 0 var iv : [UInt8] = [56, 101, 63, 23, 96, 182, 209, 205] // I didn't use let operation: CCOperation = UInt32(kCCDecrypt) let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES) let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding) let keyLength = size_t(kCCKeySize3DES) var decrypt_status : CCCryptorStatus = CCCrypt(operation, algoritm, options, keyData.bytes, keyLength, nil, decryptData.bytes, mydata_len, buffer, buffer_size, &num_bytes_encrypted) if UInt32(decrypt_status) == UInt32(kCCSuccess){ var myResult : NSData = NSData(bytes: buffer, length: num_bytes_encrypted) free(buffer) println("decrypt \(myResult)") var stringResult = NSString(data: myResult, encoding:NSUTF8StringEncoding) println("my decrypt string \(stringResult!)") return myResult }else{ free(buffer) return nil } }
我希望这可以帮助别人。