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
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.