Last active
December 24, 2015 22:19
-
-
Save bwhite/6871522 to your computer and use it in GitHub Desktop.
Simple example
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/dsa" | |
import "crypto/rand" | |
import "fmt" | |
import "math/big" | |
func SignatureGenerateServerKey() *dsa.PrivateKey { | |
priv := dsa.PrivateKey{} | |
dsa.GenerateParameters(&priv.Parameters, rand.Reader, dsa.L3072N256) | |
dsa.GenerateKey(&priv, rand.Reader) | |
return &priv | |
} | |
func SignatureSign(hash []byte, priv *dsa.PrivateKey) (r, s []byte, err error) { | |
ri, si, err := dsa.Sign(rand.Reader, priv, hash) | |
if err != nil { | |
return nil, nil, err | |
} | |
r, err = ri.MarshalJSON() | |
if err != nil { | |
return nil, nil, err | |
} | |
s, err = si.MarshalJSON() | |
if err != nil { | |
return nil, nil, err | |
} | |
return r, s, nil | |
} | |
func SignatureVerify(hash []byte, priv *dsa.PrivateKey, r []byte, s []byte) bool { | |
var ri, si big.Int | |
if ri.UnmarshalJSON(r) != nil { | |
return false | |
} | |
if si.UnmarshalJSON(s) != nil { | |
return false | |
} | |
return dsa.Verify(&priv.PublicKey, hash, &ri, &si) | |
} | |
func main() { | |
priv := SignatureGenerateServerKey() | |
hash := []byte("this is a message") | |
r, s, err := SignatureSign(hash, priv) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Println(string(r)) | |
fmt.Println(string(s)) | |
if SignatureVerify(hash, priv, r, s) { | |
fmt.Println("Signature pass") | |
} else { | |
fmt.Println("Signature fail") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment