Last active
October 10, 2022 16:38
-
-
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)
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" | |
"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 | |
} |
Good evening
Please do you have some way to generate oly the ECDSA public keys from the private keys in sequence using this library "github.com/ethereum/go-ethereum/crypto/secp256k1"
Thanks this helped a lot!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was very helpful (working on my first go project). Thanks. Cheers!