How to do AES 128 encryption of a string in Swift using Xcode and send it as POST to the server?

后端 未结 2 1008
广开言路
广开言路 2021-01-25 10:58

How to do AES 128 encryption of a string in Swift using Xcode and send it as POST to the server?... I am new to Xcode and am learning to encrypt the string data and want to send

相关标签:
2条回答
  • 2021-01-25 11:06

    Based on examples from: https://github.com/krzyzanowskim/CryptoSwift

    To encrypt a string using 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
    }
    

    To decrypt:

    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
    }
    

    To send the values to server look up: HTTP Request in Swift with POST method or any one of the thousands of posts how to send data to server.

    0 讨论(0)
  • 2021-01-25 11:21

    Add #import <CommonCrypto/CommonCryptor.h> to your Bridging Header then use the following:

    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
    }
    

    To send it to the server, base64-encode the result, and send that. Then on the server side, base64-decode the result and decrypt it.

    0 讨论(0)
提交回复
热议问题