Java MD5 签名生成 Go 语言实现
Java MD5 签名生成 Go 语言实现
本文提供将 Java 代码中使用 MD5 算法生成签名的代码转换为 Go 语言实现的示例。
Java 代码
public void test() throws Exception {
String customerKey='98dad497159e901b45c020d30bff9baf';
String requestBody ='{
' +
' 'agentCode': 'HKAD',
' +
' 'agentIDs': 'HKAD',
' +
' 'airlineCode': 'GA',
' +
' 'limit': 2,
' +
' 'offset': 2
' +
'}';
String requestStr = Hex.encodeHexString(compressionProvider.compressString(requestBody));//1、请求主体内容转换成16进制串
byte[] requestBytes=requestStr.getBytes();//2、取请求主体部分的byte
char[] customerKeyChar=customerKey.toCharArray();//3、取用户KEY的char
byte[] customerKeyBytes=Hex.decodeHex(customerKeyChar);//4、对用户KEY解码
byte[] signCodeBytes=createSignCode(requestBytes,customerKeyBytes,'MD5');//5、生成MD5签名
String SignCode=Hex.encodeHexString(signCodeBytes);
}
public byte[] createSignCode(byte[] text, byte[] key, String algorithm) throws Exception {//MD5生成签名过程
byte[] source = new byte[text.length + key.length];
System.arraycopy(text, 0, source, 0, text.length);
System.arraycopy(key, 0, source, text.length, key.length);
MessageDigest md = MessageDigest.getInstance(algorithm);
return md.digest(source);
}
Go 代码
import (
'crypto/md5'
'encoding/hex'
)
func Test() {
customerKey := '98dad497159e901b45c020d30bff9baf'
requestBody := `{
'agentCode': 'HKAD',
'agentIDs': 'HKAD',
'airlineCode': 'GA',
'limit': 2,
'offset': 2
}`
compressionProvider := // 从上下文中获取compressionProvider
requestStr := hex.EncodeToString(compressionProvider.CompressString(requestBody)) // 1、请求主体内容转换成16进制串
requestBytes := []byte(requestStr) // 2、取请求主体部分的byte
customerKeyBytes, _ := hex.DecodeString(customerKey) // 4、对用户KEY解码
signCodeBytes := createSignCode(requestBytes, customerKeyBytes, 'MD5') // 5、生成MD5签名
signCode := hex.EncodeToString(signCodeBytes)
}
func createSignCode(text []byte, key []byte, algorithm string) []byte { // MD5生成签名过程
source := make([]byte, len(text)+len(key))
copy(source, text)
copy(source[len(text):], key)
hash := md5.New()
hash.Write(source)
return hash.Sum(nil)
}
代码解释
- 1、请求主体内容转换成16进制串
- Java 代码中使用
Hex.encodeHexString(compressionProvider.compressString(requestBody))将请求主体内容转换成16进制串。 - Go 代码中使用
hex.EncodeToString(compressionProvider.CompressString(requestBody))实现相同功能。
- Java 代码中使用
- 2、取请求主体部分的byte
- Java 代码中使用
requestStr.getBytes()获取请求主体部分的字节数组。 - Go 代码中使用
[]byte(requestStr)获取字节数组。
- Java 代码中使用
- 3、取用户KEY的char
- Java 代码中使用
customerKey.toCharArray()获取用户KEY的字符数组。 - Go 代码中没有直接获取字符数组的步骤,因为 Go 语言中字符串本身就是字符数组。
- Java 代码中使用
- 4、对用户KEY解码
- Java 代码中使用
Hex.decodeHex(customerKeyChar)对用户KEY解码。 - Go 代码中使用
hex.DecodeString(customerKey)对用户KEY解码。
- Java 代码中使用
- 5、生成MD5签名
- Java 代码中使用
createSignCode(requestBytes,customerKeyBytes,'MD5')生成MD5签名。 - Go 代码中使用
createSignCode(requestBytes, customerKeyBytes, 'MD5')生成MD5签名。
- Java 代码中使用
总结
本文展示了将 Java 代码中使用 MD5 算法生成签名的代码转换为 Go 语言实现的示例。通过使用 Go 语言的 crypto/md5 和 encoding/hex 包,可以轻松地实现 MD5 签名生成功能。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/oOG2 著作权归作者所有。请勿转载和采集!