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

后端 未结 2 1013
广开言路
广开言路 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:21

    Add #import to your Bridging Header then use the following:

    func encryptAES128(data: NSData, key: NSString, iv: NSString) -> NSData? {
        let keyPtr = UnsafeMutablePointer.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.

提交回复
热议问题