如何在swift XCODE上对字符串进行AES 128加密并将其作为POST发送到服务器?

时间:2017-09-28 12:27:28

标签: ios swift xcode encryption aes

如何在swift XCODE上对字符串进行AES 128加密并将其作为POST发送到服务器?... 我是XCODE的新手,我正在学习加密字符串数据并希望发送到HTTP服务器。它是用于发送设备的纬度和经度的基本iOS应用程序。

2 个答案:

答案 0 :(得分:5)

基于以下示例:https://github.com/krzyzanowskim/CryptoSwift

使用CryptoSwift加密字符串:

func encrypt(text: String) -> String?  {
    if let aes = try? AES(key: "passwordpassword", iv: "drowssapdrowssap"),
       let encrypted = try? aes.encrypt(Array(text.utf8)) {
        return encrypted.toHexString()
    }
    return nil
}

要解密:

func decrypt(hexString: String) -> String? {
    if let aes = try? AES(key: "passwordpassword", iv: "drowssapdrowssap"),
        let decrypted = try? aes.decrypt(Array<UInt8>(hex: hexString)) {
        return String(data: Data(bytes: decrypted), encoding: .utf8)
    }
    return nil
}

要将值发送到服务器查找: HTTP Request in Swift with POST method或数千个帖子中的任何一个如何将数据发送到服务器。

答案 1 :(得分:3)

#import <CommonCrypto/CommonCryptor.h>添加到您的桥接标头,然后使用以下内容:

func encryptAES128(data: NSData, key: NSString, iv: NSString) -> NSData? {
    let keyPtr = UnsafeMutablePointer<CChar>.allocate(capacity: Int(kCCKeySizeAES128) + 1)

    defer {
        keyPtr.deallocate(capacity: Int(kCCKeySizeAES128) + 1)
    }

    let ivPtr = iv.utf8String
    bzero(keyPtr, 0)
    key.getCString(keyPtr, maxLength: Int(kCCKeySizeAES128) + 1, encoding: String.Encoding.utf8.rawValue)

    let bufferSize = data.length + kCCBlockSizeAES128
    let buffer = UnsafeMutableRawPointer.allocate(bytes: bufferSize, alignedTo: MemoryLayout.alignment(ofValue: CChar.self))

    var numBytesEncrypted = 0

    let cryptStatus = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), keyPtr, kCCKeySizeAES128, ivPtr, data.bytes, data.length, buffer, bufferSize, &numBytesEncrypted)

    if cryptStatus == kCCSuccess {
        return NSData(bytesNoCopy: buffer, length: numBytesEncrypted, freeWhenDone: true)
    }

    buffer.deallocate(bytes: bufferSize, alignedTo: MemoryLayout.alignment(ofValue: CChar.self))
    return nil
}

要将其发送到服务器,请对结果进行base64编码,然后发送。然后在服务器端,base64解码结果并解密。