billyhafiz billyhafiz -4 years ago 144
Swift Question

Can't convert encrypted data to String

I am trying to learn to use RNCryptor. Here is what I am using:

let key = "1234"
let original_text = "hello"
let data = original_text.data(using: .utf8)!
let encrypted_data = RNCryptor.encrypt(data: data, withPassword: key)

print(String(data: encrypted_data, encoding: .utf8))


This prints 'nil'. How can I convert
encrypted_data
to a String?

Also, this does work:

try! print(String(data: RNCryptor.decrypt(data: encrypted_data, withPassword: key), encoding: .utf8))


but this is the original text and not the cipher text.

Answer Source

The encrypted data is a binary blob, and in most cases not a valid UTF-8 sequence. Therefore the conversion to a string

String(data: encrypted_data, encoding: .utf8)

fails and returns nil. If you want a string representation of the encrypted data then you can use (for example) the Base64 encoding:

print(encrypted_data.base64EncodedString())

or, using

extension Data {
    func hexEncodedString() -> String {
        return map { String(format: "%02hhx", $0) }.joined()
    }
}

from How to convert Data to hex string in swift, as a hex-encoded string:

print(encrypted_data.hexEncodedString())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download