UUID interop with c# code

后端 未结 3 478
半阙折子戏
半阙折子戏 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-11 09:53

    If all you need is the same UUID string (and not actual UUID/Guid objects), this C# method will return the same value as Java's UUID.nameUUIDFromBytes(byte[]) method.

    public static string NameUUIDFromBytes(byte[] input)
    {
        MD5 md5 = MD5.Create();
        byte[] hash = md5.ComputeHash(input);
        hash[6] &= 0x0f;
        hash[6] |= 0x30;
        hash[8] &= 0x3f;
        hash[8] |= 0x80;
        string hex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
        return hex.Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-");
    }
    

    C# Example

    string test = "test";
    Console.Out.WriteLine(NameUUIDFromBytes(Encoding.UTF8.GetBytes(test)));
    
    Output:
    098f6bcd-4621-3373-8ade-4e832627b4f6
    

    Java Example

    UUID test = UUID.nameUUIDFromBytes("test".getBytes("UTF-8"));
    System.out.println(test);
    
    Output:
    098f6bcd-4621-3373-8ade-4e832627b4f6
    

    Edit: I know it's after the fact, but this will produce an actual Guid object with the same value. Just incase anyone wants it.

    public static Guid NameGuidFromBytes(byte[] input)
    {
        MD5 md5 = MD5.Create();
        byte[] hash = md5.ComputeHash(input);
        hash[6] &= 0x0f;
        hash[6] |= 0x30;
        hash[8] &= 0x3f;
        hash[8] |= 0x80;
    
        byte temp = hash[6];
        hash[6] = hash[7];
        hash[7] = temp;
    
        temp = hash[4];
        hash[4] = hash[5];
        hash[5] = temp;
    
        temp = hash[0];
        hash[0] = hash[3];
        hash[3] = temp;
    
        temp = hash[1];
        hash[1] = hash[2];
        hash[2] = temp;
        return new Guid(hash);
    }
    

提交回复
热议问题