php hmac_sha256 and go hmac sha256 have different results
data="hello, bruce" secret = "abc123"
Php, the result of hmac_sha256 is, 49c7d9cad6ec999aed5e683ade84a14382e9e2af1fd22a03236c49f4e7e3e483
$msg = "hi bruce";
$secret = "abc123";
echo hash_hmac("sha256", $msg, $secret);
go hmac sha256的结果是, 68692062727563656d2d9fc610337f813a1b85869ec214129940860543ad04308d87357f6c0133f6
data := []byte("hi bruce")
key := []byte("abc123")
m := hmac.New(sha256.New, key)
result := m.Sum(data)
fmt.Println(hex .EncodeToString(result))
The two results are different, and then I adjusted the code of go, and finally the same
data := []byte("hi bruce")
key := []byte("abc123")
m := hmac.New(sha256.New, key)
_,_ =m.Write(data)
result := m Why does .Sum(nil)
fmt.Println(hex.EncodeToString(result))
work like this?
php uses sha256 to encrypt the result,
$msg = "hi bruce";
echo hash("sha256", $msg);
// fd0ba5023ae46431c1f621d3fdd58464f27241032bf13b98d6a81773d48d4da1 At
this time, PHP and go generate the same
When we encrypt a message with sha256, we can directly put the data in the sum, or we can write the data first, and the result of sum (nil) is the same
data := []byte("hi bruce")
tmp:= sha256.Sum256(data)
fmt.Println(hex.EncodeToString(tmp[:]))
m1 := sha256.New()
_,_=m1.Write(data)
fmt.Println(hex.EncodeToString(m1.Sum(nil)))
//运行结果如下
//fd0ba5023ae46431c1f621d3fdd58464f27241032bf13b98d6a81773d48d4da1
//fd0ba5023ae46431c1f621d3fdd58464f27241032bf13b98d6a81773d48d4da1
In hmac, we are accustomed to thinking the same, so there is surprise, but the result is different
But it's different in go's hmac, because hmac calls sha256 multiple times, pay attention to inertial thinking