
import cn.hutool.crypto.digest.HMac; import cn.hutool.crypto.digest.HmacAlgorithm; public class SignTest { public static void main(String[] args) { // 应用 ID String appId = ""; // 应用 secret String appSecret = ""; // 请求时间戳(发送请求的时间戳) String timestamp = ""; // 随机字符串 (自定义随机字符串) String nOnce= ""; // 请求 body (请求 body , 需保证发送方与接收方的数据一致,建议在拦截器里做对应认证) String body = ""; // 签名串 String signCOntent= String.format("%s\n%s\n%s\n%s\n", appId, timestamp, nonce, body); // 签名值 HMac hMac = new HMac(HmacAlgorithm.HmacSHA1, appSecret.getBytes()); String signature = hMac.digestHex(signContent); System.out.println(signature); } } $sudAppId = '1719669845797171201'; $sudTimestamp = '1698912908000'; $sudNOnce= 'lFM9MKckbGYiZAQG'; $body = '{"platform":2}'; $signCOntent= $sudAppId . '\n' . $sudTimestamp . '\n' . $sudNonce . '\n . json_encode($body) .'\n'; $appSecret = 'test'; $signatureString = $signContent; $sign = hash_hmac('sha1', $signatureString, $appSecret,false); echo $sign; 1 cian 2023 年 11 月 2 日 via Android gptchat |
3 guanhui07 OP ```nodejs const Crypto = require('crypto'); function signTest() { let appId = '1719669845797171201'; let appSecret = 'test'; let timestamp = '1698912908000'; let nOnce= 'lFM9MKckbGYiZAQG'; let body = '{"platform":2}'; let signCOntent= appId + '\n' + timestamp + '\n' + nonce + '\n' + body + '\n'; let hmac = Crypto.createHmac('sha1', appSecret); let signature = hmac.update(signContent).digest('hex'); console.log(signature); } ```` php 写出来了 结果 和 java 一样 |
6 sujin190 2023 年 11 月 2 日 via Android php 的 bode 为啥要 json_encode ,这肯定不一样了啊 |
7 dw2693734d 2023 年 11 月 2 日 我被你说晕了,你到底想干啥 |
8 dw2693734d 2023 年 11 月 2 日 json_encode($body) 这里错了 |
9 sl0000 2023 年 11 月 2 日 hmac 一般要做一个 key 排序 |
10 guanhui07 OP @sujin190 #6 我的小例子 写错了 ```php <?php $sudAppId = '1719669845797171201'; $sudTimestamp = '1698912908000'; $sudNOnce= 'lFM9MKckbGYiZAQG'; $body = '{"platform":2}'; $signCOntent= $sudAppId . '\n' . $sudTimestamp . '\n' . $sudNonce . '\n' . $body .'\n'; $appSecret = 'test'; $sign = hash_hmac('sha1', $signContent, $appSecret,false); echo $sign; ``` 这种也不行 , 试了下 sign 出来 和 java node golang 的 不一致 ```golang package main import ( "crypto/hmac" "crypto/sha1" "fmt" ) func main() { // 应用 ID var appId = "1719669845797171201" // 应用 secret var appSecret = "test" // 请求时间戳(发送请求的时间戳) var timestamp = "1698912908000" // 随机字符串 (自定义随机字符串) var nOnce= "lFM9MKckbGYiZAQG" // 请求 body (请求 body , 需保证发送方与接收方的数据一致,建议在拦截器里做对应认证) var body = "{\"platform\":2}" // 签名串 signContent := fmt.Sprintf("%s\n%s\n%s\n%s\n", appId, timestamp, nonce, body) // 签名值 mac := hmac.New(sha1.New, []byte(appSecret)) mac.Write([]byte(signContent)) signature := mac.Sum(nil) //t.Logf("signature:%x", signature) test, _ := fmt.Printf("signature:%x", signature) fmt.Println(test) } ``` golang 的可以 |
11 guanhui07 OP 在某位大佬指点下解决了 |