How to verify a digital signature in Go?

To verify a digital signature in Go, you can follow these steps:

  1. Import the required packages:
import ( "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/pem" "fmt" "io/ioutil" )
  1. Read the public key from a file:
publicKeyData, err := ioutil.ReadFile("public_key.pem") if err != nil { fmt.Println("Error reading public key:", err) return }
  1. Parse the public key from the PEM format:
publicKeyBlock, _ := pem.Decode(publicKeyData) if publicKeyBlock == nil || publicKeyBlock.Type != "PUBLIC KEY" { fmt.Println("Failed to parse PEM block containing public key") return } publicKey, err := x509.ParsePKIXPublicKey(publicKeyBlock.Bytes) if err != nil { fmt.Println("Error parsing public key:", err) return } rsaPublicKey, ok := publicKey.(*rsa.PublicKey) if !ok { fmt.Println("Failed to get RSA public key") return }
  1. Read the data and signature from their respective files:
data, err := ioutil.ReadFile("data.txt") if err != nil { fmt.Println("Error reading data file:", err) return } signature, err := ioutil.ReadFile("signature.txt") if err != nil { fmt.Println("Error reading signature file:", err) return }
  1. Verify the signature using the public key:
hashed := sha256.Sum256(data) err = rsa.VerifyPKCS1v15(rsaPublicKey, crypto.SHA256, hashed[:], signature) if err != nil { fmt.Println("Signature verification failed:", err) return } fmt.Println("Signature is valid")

This code reads a public key from a pem file, reads the data and signature from their respective files, and then verifies the signature using the public key and the data. If the verification is successful, it prints "Signature is valid".

Note: Make sure you have the necessary files for public key, data, and signature, and replace the file paths with the correct ones in your case.