Created
December 22, 2020 15:47
-
-
Save superj80820/5a32a26f1bdf4b9829a497b6d007d111 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
// 大量參考: https://gist.github.com/mfridman/c0c5ece512f63d429c4589196a1d4242 | |
package main | |
import ( | |
"crypto" | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/sha512" | |
"crypto/x509" | |
"encoding/pem" | |
"fmt" | |
"io/ioutil" | |
"log" | |
) | |
// LoadFile load the file to bytes | |
func LoadFile(path string) []byte { | |
content, err := ioutil.ReadFile(path) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return content | |
} | |
// BytesToPrivateKey bytes to private key | |
func BytesToPrivateKey(priv []byte) *rsa.PrivateKey { | |
block, _ := pem.Decode(priv) | |
enc := x509.IsEncryptedPEMBlock(block) | |
b := block.Bytes | |
var err error | |
if enc { | |
log.Println("is encrypted pem block") | |
b, err = x509.DecryptPEMBlock(block, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
key, err := x509.ParsePKCS1PrivateKey(b) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return key | |
} | |
func main() { | |
// 壞人的私鑰 | |
badGuyPrivateKey := BytesToPrivateKey(LoadFile("./badGuyKey")) | |
// 小明的私鑰 | |
goodGuyPrivateKey := BytesToPrivateKey(LoadFile("./goodGuyKey")) | |
// 小明的公鑰,公鑰可以透過私要來取得,所以這邊就不在載入公鑰檔案了 | |
goodGuyPublicKey := goodGuyPrivateKey.PublicKey | |
// 小明用自己的私鑰對訊息簽章 | |
messageBytes := []byte("小明餐點: 大冰奶") | |
hash := sha512.New() | |
hash.Write(messageBytes) | |
hashed := hash.Sum(nil) | |
// 小明用自己的私鑰簽名 | |
signature, err := rsa.SignPKCS1v15(rand.Reader, goodGuyPrivateKey, crypto.SHA512, hashed) | |
if err != nil { | |
panic(err) | |
} | |
// 小明的資料被壞人攔截,壞人開始偽造小明的訊息 | |
messageBytes = []byte("小明餐點: 大冰紅") | |
hash = sha512.New() | |
hash.Write(messageBytes) | |
hashed = hash.Sum(nil) | |
// 壞人用自己的私鑰簽名,並非小明的 | |
signature, err = rsa.SignPKCS1v15(rand.Reader, badGuyPrivateKey, crypto.SHA512, hashed) | |
if err != nil { | |
panic(err) | |
} | |
// 早餐店阿姨取得小明的公鑰,利用此公鑰驗證之後發現不是小明傳的訊息 | |
err = rsa.VerifyPKCS1v15(&goodGuyPublicKey, crypto.SHA512, hashed, signature) | |
if err != nil { | |
fmt.Println("Two signatures are not the same. Error: ", err) | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment