Search code examples
swiftencryptioncryptographyaesnsdata

swift aes 128 decryption with string input


I'm using zaph's example for encryption and decryption from this post

The encryption works well, and with my encryption key and iv, returns an NSData object, containing the following string: "bc6983a8 65d412df 2bafdc40 f569874e", which is my input text encrypted. The content of the returned NSData object:

encrypted text: <bc6983a8 65d412df 2bafdc40 f569874e>

This text is sent to a server (json), and the server returns a response, also encrypted with the same encryption key and iv.

My question is, how can I convert the string text that comes from the server's response(bc6983a8 65d412df 2bafdc40 f569874e, for example) into an NSData object so that i can decrypt it?

I tried the follwing:

let plainData = ("<bc6983a8 65d412df 2bafdc40 f569874e>" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!;

let plainData = ("<bc6983a8 65d412df 2bafdc40 f569874e>" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!;
let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let dataDec = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))

But when displaying the contents of the NSData object, the output is not the one expected:

data Optional("<3c626336 39383361 38203635 64343132 64662032 62616664 63343020 66353639 38373465 3e>")

Any help is appreciated.


Solution

  • You are converting your NSData to the string in a wrong way. Follow this code to convert NSData to string

    //This is your encrypted data
    var encryptedData = NSData()
    let plainData = encryptedData(data: encryptedData, encoding: NSUTF8StringEncoding)
    

    Hope this will work for you.

    UPDATE: This happens because you are not correctly fetching the string from your backend. Use proper method for decoding json data instead of just printing it. "<bc6983a8 65d412df 2bafdc40 f569874e>" is not the string you actually need. You need to decode your json data

    See the sample code

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in
    
                if error != nil
                {
                    print("error=\(error)", terminator: "")
                    return
                }
     do{   if let newdata =  try? (NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary)
                {
    
                    print(newdata)
    
    
                    }
    

    Here 'newdata' may include the encrypted string you need. Parse it from that json, convert it to NSData and then decrypt.

    UPDATE 2 Use this code to convert your data to string

    let resstr = NSString(data: YourData, encoding: NSUTF8StringEncoding)