3

I am using CryptoSwift to encrypt data I will be passing in a URL. To do this, I need the datatype of the piece of data to be a String to concatenate into the NSURL request. After encrypting the data it is output in bytes. How can I cast the bytes to a nonsense string to pass in the URL that a PHP script can decrypt?

I am able to encrypt into UInt8, however I do not think it is possible to pass it over a URL to PHP script so I need to make it a string.

The code:

let string = "hello"
let input: [UInt8] = Array(string.utf8)
let key: [UInt8] = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
let iv: [UInt8] = AES.randomIV(AES.blockSize)
do {
    let encrypted: [UInt8] = try AES(key: key, iv: iv, blockMode: .CBC).encrypt(input, padding: PKCS7())
    print("Encrypted bytes: \(encrypted)")
    let str = String(bytes: encrypted, encoding: NSUTF8StringEncoding)
    print("String of encrypted data: \(str)") // prints a nil value
} catch AES.Error.BlockSizeExceeded {
    print("Block size exceeded")
} catch {
    print("Error encrypting or decrypting data")
}

Thank you very much for the help,

jww
  • 97,681
  • 90
  • 411
  • 885
iamnickpitoniak
  • 227
  • 1
  • 4
  • 11

1 Answers1

4
  1. Do not use CryptoSwift, it is neither fast (500-1000 times slower than Common Crypto) nor secure (it lacks substantial vetting).

  2. Encrypted data is undistinguishable from random data bytes.

  3. Not all data arrays are convertible to strings in any encoding. There are many data bytes that do not have a printable representation or any representation in a string encoding. That is why raw data bytes are generally encoded to Base64 or hexadecimal strings.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • can you elaborate on how one would cast the bytes I am using to a Base64, hexadecimal string, or other datatype that can be concatenated into a URL? Thanks – iamnickpitoniak Dec 26 '15 at 22:27
  • It is not casting, it is encoding. Apple does not supply hexadecimal methods, the best is to use the Base64 methods of `NSData`. – zaph Dec 26 '15 at 23:17