Created
December 22, 2020 15:47
-
-
Save superj80820/39912bf29b370cb3cfd348f36bab74e1 to your computer and use it in GitHub Desktop.
Markdium-Week39 - 各種安全性演算法的應用 - 竊聽、電子欺騙實作
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/hmac" | |
"crypto/sha256" | |
"encoding/hex" | |
"fmt" | |
) | |
func hmacSha256(data string, secret string) string { | |
h := hmac.New(sha256.New, []byte(secret)) | |
h.Write([]byte(data)) | |
return hex.EncodeToString(h.Sum(nil)) | |
} | |
func main() { | |
sharedSecret := "小明與早餐店阿姨的共同鑰匙" | |
badGuySecret := "壞人的鑰匙" | |
meals := "小明餐點: 大冰紅" | |
// 小明利用與早餐店阿姨共同的鑰匙產生HMAC | |
requestHMAC := hmacSha256(meals, sharedSecret) | |
// 壞人攔截小明的封包,利用自己的鑰匙產生HMAC | |
requestHMAC := hmacSha256(meals, badGuySecret) | |
// 早餐店阿姨利用與小明共同的鑰匙產生HMAC | |
trueHMAC := hmacSha256(meals, sharedSecret) | |
// 早餐店阿姨比對此兩個HMAC,發現不同,故此訊息不是小明傳送的 | |
if requestHMAC != trueHMAC { | |
fmt.Println("Two HMACs are not the same.") | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment