title: iOS Swift: AES key+salt decryption
body: <p>I am currently trying to decrypt a JWT Token using the PBE AES Encryption, but the problem that I am facing is that the value always returns nil when i try to convert the data received after decryption. I am using CryptoSwift and CommonCrypto to do the needful. Below are the snippets of my codebase. </p>
  
  <p>This is how I am trying to convert the key and salt to the respective key that can be used for decryption.</p>
  
  <pre><code>let keyData:NSData = PRIVATE_KEY.dataUsingEncoding(NSUTF8StringEncoding)!;
      let saltData:NSData = SALT_KEY.dataUsingEncoding(NSUTF8StringEncoding)!;
  
      var hashkeyData:NSMutableData = NSMutableData(length:kCCKeySizeAES256)!;
  
      let ptr = UnsafePointer&lt;Int8&gt;(keyData.bytes)
      let saltPtr = UnsafePointer&lt;UInt8&gt;(saltData.bytes);
      let hashKeyPtr = UnsafeMutablePointer&lt;UInt8&gt;(hashkeyData.mutableBytes);
      let result = CCKeyDerivationPBKDF(UInt32(kCCPBKDF2), ptr, keyData.length, saltPtr, saltData.length, UInt32(kCCPRFHmacAlgSHA256), 1000, hashKeyPtr, hashkeyData.length);
  
      assert(result == Int32(kCCSuccess),"Unable to create AES key for password: \(result)");
  
      return hashkeyData as NSData;
  </code></pre>
  
  <p>Here is the code for the decryption.</p>
  
  <pre><code>    let encodedData = encryptedToken.dataUsingEncoding(NSUTF8StringEncoding);
          let encodedBase64Data = NSData(base64EncodedString: encryptedToken ,options: []);
          let encodedDataArray = encodedBase64Data?.arrayOfBytes();
  
          let stringData = NSString(data: encodedBase64Data!, encoding: NSUTF8StringEncoding);
          print("Base 64 Encoded Data: \(stringData)");
  
          let keyData = self.getPBEKey();
          let keyDataArray = keyData.arrayOfBytes();
          let keyVal:[UInt8] = Array(keyDataArray[0...31]);
  
          let ivDataArray = Array(keyDataArray[0...15]);
  
          let decryptedData:[UInt8]?;
  
          do {
              let aesObject = AES(key: keyVal, iv: ivDataArray, blockMode: .CBC);
  
              decryptedData = try aesObject?.decrypt(encodedDataArray!,padding: PKCS7());
              let convertedData = NSData(bytes: decryptedData!, length: decryptedData!.count);
  print("Decrypted Data: \(String(data:convertedData, encoding: NSUTF8StringEncoding)))")             
  
          } catch {
              print("Error \(error)");
          }
  </code></pre>
  
  <p>The problem that I am currently facing is the value for the <strong>Decrypted Data</strong> always comes out to be nil which should be a valid JWT Token. </p>
  
  <p>Has someone encountered such kind of situation earlier or else is there something that I am missing in the above code which is leading to the issue.</p>