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 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面