The NewPublicKey
function from the crypto/ssh package http://godoc.org/golang.org/x/crypto/ssh#NewPublicKey can take an *rsa.PublicKey
as parameter and returns an instance of the PublicKey
interface that includes a Verify
method (Verify(data []byte, sig *Signature) error
) - http://godoc.org/golang.org/x/crypto/ssh#PublicKey.
The program below illustrates it - we create a new *rsa.PrivateKey and sign a message with it, then convert *rsa.PublicKey
to ssh.PublicKey
using NewPublicKey
function and verify the signature; also check that the signature verification fails if the original data is modified. The error checking is elided for brevity.
package main
import (
"crypto/rand"
"crypto/rsa"
"fmt"
"log"
"golang.org/x/crypto/ssh"
)
func main() {
data := []byte("Hello, world!")
// create a new key as *rsa.PrivateKey
priv, _ := rsa.GenerateKey(rand.Reader, 512)
signer, _ := ssh.NewSignerFromKey(priv)
sig, _ := signer.Sign(rand.Reader, data)
// extract the ssh.PublicKey from *rsa.PublicKey to verify the signature
pub, _ := ssh.NewPublicKey(&priv.PublicKey)
if err := pub.Verify(data, sig); err != nil {
log.Fatalf("publicKey.Verify failed: %v", err)
}
fmt.Printf("Signature OK
")
// modify the data and make sure we get a failure
data[0]++
if err := pub.Verify(data, sig); err == nil {
log.Printf("publicKey.Verify passed on bad data/signature, expect failure")
}
}
Output:
Signature OK