UUID interop with c# code

后端 未结 3 487
半阙折子戏
半阙折子戏 2021-02-11 09:22

Can c# donet generate same UUID for following java code? if so how? i tried GUID but didn\'t work!

Text:

String cleartext = \"CN=CompanyName;mac=some mac         


        
3条回答
  •  深忆病人
    2021-02-11 10:15

    This code is definitely not going to work with .NET.

    The Guid(Byte[]) constructor must take in 16 bytes (as Guids are 128 bits), otherwise it will throw an ArgumentException. Your string is much more than 16 bytes.

    However, with that said, C# and Java will still not produce the same UUIDs using the same 16 bytes passed into the constructor. In Java, you can pass in any arbitrary number of bytes into the UUID constructor and it will create a hash of those bytes. In other words:

    In C#:

    Guid g = new Guid(new Byte[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16});
    Console.WriteLine(g);
    

    Will produce a different value than:

    UUID u = UUID.nameUUIDFromBytes(new byte[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16});
    System.out.println(u);
    

    ...in Java.

    You could probably implement .NET's Byte[16] constructor in Java, or implement Java's hash constructor in .NET, but I would suggest using a string representation of your UUID across both platforms, for example, "190c4c10-5786-3212-9d85-018939108a6c".

    If you're trying to create a hash from a string, you might want to check into the MD5 class. You'd want something like:

    var md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(cleartext);
    byte[] hashBytes  = md5.ComputeHash(inputBytes);
    

    MD5 is a standard algorithm and will produce the same hash for the same string in both .NET and Java.

提交回复
热议问题