首页 > 解决方案 > 查找字符串的 MSB 和 LSB

问题描述

我需要在 Go 中执行以下操作:

  1. 连接 2 个字符串
  2. 计算连接字符串的 MD5 哈希(128 位数组)
  3. 对 MD5 哈希上的 64 个 LSB 和 64 个 MSB 应用 XOR 运算符。

我可以使用“crypto/md5”包计算字符串的 MD5 哈希,但在执行步骤 3 时遇到了麻烦。这是我想出的代码,我认为它是不正确的,并且没有看到任何从字符串中获取 MSB 和 LSB 的链接。

func GenerateHashKey(s1 string, s2 string) string {
    if s1 == "" {
        return ""
    }

    data := []byte(s1 + s2)
    md5sum := md5.Sum(data)
    
    // 0: uint32
    lsb := bytes.NewBuffer(md5sum[:9]) // 0-8
    msb := bytes.NewBuffer(md5sum[9:]) // 9-16
    return msb ^ lsb; //This results in an error
}

这是我需要翻译成 Go 的相应工作 Java 代码。

//input is a concatenated string
byte[] str = input.getBytes("UTF-8");
byte[] md5sum = MessageDigest.getInstance("MD5").digest(str);
long lsb =
ByteBuffer.wrap(md5sum).order(ByteOrder.LITTLE_ENDIAN).getLong(0);
long msb =
ByteBuffer.wrap(md5sum).order(ByteOrder.LITTLE_ENDIAN).getLong(8);
return msb ^ lsb;

标签: gobytexor

解决方案


您不能在 a 上使用按位运算符bytes.Buffer,它仅适用于整数值。您可以使用encoding/binary包将字节转换为合适的 64 位值以进行 XOR,并在此处使用 little endian 字节顺序,如提供的 java 代码所示。

获得值后,您可以根据需要使用fmt.Sprintfstrconv包格式化返回的字符串。


func GenerateHashKey(s1 string, s2 string) string {
    data := []byte(s1 + s2)
    md5sum := md5.Sum(data)

    lsb := binary.LittleEndian.Uint64(md5sum[:8])
    msb := binary.LittleEndian.Uint64(md5sum[8:])
    return strconv.FormatUint(lsb^msb, 10)
}

推荐阅读