-
-
Save developer-guy/b7b409492d48f422beb91cb06f665919 to your computer and use it in GitHub Desktop.
Sign a message and verify signature with go using PKCS1. Compatible with java (SHA256withRSA)
This file contains hidden or 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" | |
"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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment