To sign data using asymmetric key cryptography in Go, you can use the crypto
and crypto/rand
packages. Here's an example code to demonstrate the process:
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
)
func main() {
// Generate RSA key pair
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println("Error generating private key:", err)
return
}
// Create a digest of the data to be signed
data := []byte("Hello, World!")
hash := sha256.Sum256(data)
// Sign the digest using the private key
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hash[:])
if err != nil {
fmt.Println("Error signing data:", err)
return
}
fmt.Println("Data:", string(data))
fmt.Printf("Signature: %x\n", signature)
// Verify the signature using the public key (can be done by anyone)
publicKey := privateKey.PublicKey
err = rsa.VerifyPKCS1v15(&publicKey, crypto.SHA256, hash[:], signature)
if err != nil {
fmt.Println("Signature verification failed:", err)
return
}
fmt.Println("Signature verified successfully.")
}
Here's a brief explanation of the code:
rsa.GenerateKey
from the crypto/rsa
package.crypto/sha256
package.rsa.SignPKCS1v15
with the private key.rsa.VerifyPKCS1v15
with the corresponding public key. Note that the public key can be shared and used by anyone for verification.Make sure to import the required packages at the beginning of your code:
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
)
This example shows how to sign and verify data using RSA. You can also use other asymmetric key algorithms like ECDSA by replacing rsa
with ecdsa
where applicable.