Can't convert encrypted data to String

前端 未结 1 1636
星月不相逢
星月不相逢 2021-01-25 09:20

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         


        
相关标签:
1条回答
  • 2021-01-25 09:55

    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())
    
    0 讨论(0)
提交回复
热议问题