How to convert bytes to NSString after AES CryptoS

2019-05-15 10:51发布

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,

1条回答
Explosion°爆炸
2楼-- · 2019-05-15 11:37
  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.

查看更多
登录 后发表回答