Converting a byte array to string and then back again produced different results

前端 未结 2 1698
离开以前
离开以前 2021-01-12 16:12

I\'m using the .net port of libsodium. The hash generation function has two forms, one that accepts byte arrays and one that accepts strings:

public static b         


        
相关标签:
2条回答
  • 2021-01-12 16:45

    Converting a byte array to string and then back again produced different results

    A binary data may not be converted to string and then back to byte array using Encoding.[AnyEncoding].GetBytes and Encoding.[AnyEncoding].GetString

    Instead use Convert.ToBase64String and Convert.FromBase64String

    You can easily test...

    var bytes = new byte[] { 255, 255, 255 }; 
    var buf = Encoding.UTF8.GetString(bytes);
    var newbytes = Encoding.UTF8.GetBytes(buf);
    

    newbytes's length will be 9.....

    Edit: This is the test case for @Theo

    var bytes = new byte[] { 0, 216 }; //any new byte[] { X, 216 };
    var buf = Encoding.Unicode.GetString(bytes);
    var newbytes = Encoding.Unicode.GetBytes(buf); //253,255
    
    0 讨论(0)
  • 2021-01-12 17:04

    I think the problem here is that the ArgonGenerateSalt method doesn't return a UTF8 encoded string, it returns completely random bytes.

    You can't decode random bytes as a UTF8 string and expect it to round trip. A trivial example to see where this blows up is to do the following:

    var data = new byte[] { 128 };
    var dataAsString = Encoding.UTF8.GetString( data );
    var dataAsBytes = Encoding.UTF8.GetBytes( dataAsString );
    

    After this, dataAsBytes will be 3 bytes (specifically 239, 191, 189).

    0 讨论(0)
提交回复
热议问题