go - 查找字符串的 MSB 和 LSB
问题描述
我需要在 Go 中执行以下操作:
- 连接 2 个字符串
- 计算连接字符串的 MD5 哈希(128 位数组)
- 对 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;
解决方案
您不能在 a 上使用按位运算符bytes.Buffer
,它仅适用于整数值。您可以使用encoding/binary
包将字节转换为合适的 64 位值以进行 XOR,并在此处使用 little endian 字节顺序,如提供的 java 代码所示。
获得值后,您可以根据需要使用fmt.Sprintf
或strconv
包格式化返回的字符串。
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)
}
推荐阅读
- android - Android SDK:repositories.cfg 丢失
- javascript - 按下输入键时如何显示警报
- c# - 尽管已定义 WPF KeyDown 方法,但在类中找不到
- twilio - 我可以将自己的号码转发到 twilio 号码吗?
- java - 让 JavaFX 事件侦听器与我的方法对话
- nginx - nginx.conf 中的两个位置
- html - 如何在按钮单击时导航到下一页网站
- directx - DirectX 11 正面剔除不会剔除阴影贴图中的正面
- apache-spark - spark 2.2 无法处理聚合表达式中的映射列
- django - Django-rest-framework 使用 3 种内容类型如何管理渲染器和序列化器