Skip to content

Instantly share code, notes, and snippets.

@nilsmagnus
Last active October 10, 2022 16:38
Show Gist options
  • Save nilsmagnus/8cb1ff93b56f73126f65e22840cbc32b to your computer and use it in GitHub Desktop.
Save nilsmagnus/8cb1ff93b56f73126f65e22840cbc32b to your computer and use it in GitHub Desktop.
Sign a message and verify signature with go using PKCS1. Compatible with java (SHA256withRSA)
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"testing"
)
func Test_sign_a_message_and_verify_signature(t *testing.T) {
// sign part
privateKey, publicKey, err := generateKeyPair(512)
if err != nil {
t.Fatalf("could not generate keypair: %s", err.Error())
}
data := []byte("Eg vil ikkje vaska opp!")
digest := sha256.Sum256(data)
signature, signErr := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, digest[:])
if signErr != nil {
t.Errorf("Could not sign message:%s", signErr.Error())
}
// just to check that we can survive to and from b64
b64sig := base64.StdEncoding.EncodeToString(signature)
decodedSignature, _ := base64.StdEncoding.DecodeString(b64sig)
// verify part
verifyErr := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, digest[:], decodedSignature)
if verifyErr != nil {
t.Errorf("Verification failed: %s", verifyErr)
}
}
// GenerateKeyPair generates a new key pair
func generateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {
privkey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil, err
}
return privkey, &privkey.PublicKey, nil
}
@dknight
Copy link

dknight commented Oct 10, 2022

Thanks this helped a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment