Skip to content

Instantly share code, notes, and snippets.

@spjmurray
Created October 10, 2018 15:50
Show Gist options
  • Save spjmurray/483801f999b31fa0dd77f2d8b65bc00c to your computer and use it in GitHub Desktop.
Save spjmurray/483801f999b31fa0dd77f2d8b65bc00c to your computer and use it in GitHub Desktop.
DSA signing
package main
import (
"crypto/dsa"
"crypto/rand"
"crypto/sha256"
"fmt"
"math/big"
"strings"
)
func verify(pub *dsa.PublicKey, hash []byte, signature string) {
parts := strings.Split(signature, ":")
r, s := &big.Int{}, &big.Int{}
r.SetString(parts[0], 16)
s.SetString(parts[1], 16)
if dsa.Verify(pub, hash, r, s) {
fmt.Println("ok")
} else {
fmt.Println("fail")
}
}
// We could possibly hash anything, pod name is good enough
func hash(name string) []byte {
h := sha256.Sum256([]byte(name))
return h[:]
}
func main() {
fmt.Println("Generating DSA parameters ...")
params := dsa.Parameters{}
if err := dsa.GenerateParameters(&params, rand.Reader, dsa.L3072N256); err != nil {
fmt.Println(err)
return
}
fmt.Println("Generating DSA key pair ...")
key := dsa.PrivateKey{}
key.PublicKey.Parameters = params
if err := dsa.GenerateKey(&key, rand.Reader); err != nil {
fmt.Println(err)
return
}
pub := key.PublicKey
// That was slow... but we'd have the public and private key compiled into
// the operator binary...
fmt.Println("Generating DSA signature for pod ...")
h := hash("cb-example-0000")
r, s, err := dsa.Sign(rand.Reader, &key, h)
if err != nil {
fmt.Println(err)
return
}
annotation := r.Text(16) + ":" + s.Text(16)
// Works fine!
fmt.Println("Verifying DSA signature for pod ...")
h = hash("cb-example-0000")
verify(&pub, h, annotation)
// Tamper with the metadata
fmt.Println("Verifying DSA signature for pod (tampered metadata) ...")
h = hash("cb-example-0001")
verify(&pub, h, annotation)
// Tamper with the annotation
fmt.Println("Verifying DSA signature for pod (tampered signature) ...")
h = hash("cb-example-0000")
verify(&pub, h, annotation + "4")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment