1

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
twharmon
  • 4,153
  • 5
  • 22
  • 48

1 Answers1

6

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())
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382