Created
September 22, 2018 02:07
-
-
Save arrieta/937657708c87bc641eecab740d953fc4 to your computer and use it in GitHub Desktop.
Check RSA Signature (golang)
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" | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/sha256" | |
"crypto/x509" | |
"encoding/pem" | |
"fmt" | |
"io/ioutil" | |
) | |
func main() { | |
prv, err := readPrivate("NZLSpecimen") | |
if err != nil { | |
fmt.Println("Error reading private key: %v", err) | |
panic(err) | |
} | |
msg := []byte("This is the message to be signed") | |
signature, err := signMessage(msg, prv) | |
if err != nil { | |
fmt.Println("Error generating signature: %v", err) | |
panic(err) | |
} | |
pub, err := readPublic("NZLSpecimenPublic.pem") | |
if err != nil { | |
fmt.Println("Error reading public key: %v", err) | |
panic(err) | |
} | |
err = checkSignature(msg, signature, pub) | |
if err != nil { | |
fmt.Println("Signature does not match: %v", err) | |
panic(err) | |
} | |
fmt.Println("Signature matches") | |
} | |
func readPrivate(path string) (*rsa.PrivateKey, error) { | |
data, err := ioutil.ReadFile(path) | |
if err != nil { | |
fmt.Println("Error reading private key: %v", err) | |
panic(err) | |
} | |
block, _ := pem.Decode(data) | |
return x509.ParsePKCS1PrivateKey(block.Bytes) | |
} | |
func readPublic(path string) (*rsa.PublicKey, error) { | |
data, err := ioutil.ReadFile(path) | |
if err != nil { | |
fmt.Println("Error reading public key: %v", err) | |
panic(err) | |
} | |
block, _ := pem.Decode(data) | |
return x509.ParsePKCS1PublicKey(block.Bytes) | |
} | |
func signMessage(data []byte, key *rsa.PrivateKey) ([]byte, error) { | |
hasher := sha256.New() | |
hasher.Write(data) | |
hashed := hasher.Sum(nil) | |
return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hashed) | |
} | |
func checkSignature(data []byte, signature []byte, key *rsa.PublicKey) error { | |
hasher := sha256.New() | |
hasher.Write(data) | |
hashed := hasher.Sum(nil) | |
return rsa.VerifyPKCS1v15(key, crypto.SHA256, hashed, signature) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment