doupu1957 2016-07-26 02:02
浏览 127
已采纳

将rsa.PublicKey转换为ssh.PublicKey

I have an rsa.PublicKey which consists of a modulus and a public exponenet in a struct. I want to verify an ssh.Signature which is signed with that key, and I figure if I have an ssh.PublicKey I can call the Verify method on that interface. However, I can't find any classes that implement ssh.PublicKey and support converting from rsa.PublicKey. Do I need to write a proprietary method to do this, or is there some class I'm not finding, or a better way to go about solving my problem?

For context, I got the rsa.PublicKey from an x509.Certificate which came from a yubikey attesting a key in one of its PIV slots.

  • 写回答

1条回答 默认 最新

  • donglizhan7848 2016-07-26 11:25
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思