M J A
M J A

Reputation: 11

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

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 to HTTP server. It is a basic iOS app for sending Latitude and Longitude of the device.

Upvotes: 1

Views: 14658

Answers (2)

Au Ris
Au Ris

Reputation: 4669

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.

Upvotes: 12

Brandon
Brandon

Reputation: 23485

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.

Upvotes: 4

Related Questions