gpt4 book ai didi

go - 将 rsa.PublicKey 转换为 ssh.PublicKey

转载 作者:IT王子 更新时间:2023-10-29 01:42:04 25 4
gpt4 key购买 nike

我有一个 rsa.PublicKey,它由结构中的模数和公共(public)指数组成。我想验证用该 key 签名的 ssh.Signature,我想如果我有 ssh.PublicKey 我可以调用 Verify 该接口(interface)上的方法。但是,我找不到任何实现 ssh.PublicKey 并支持从 rsa.PublicKey 转换的类。我是否需要编写专有方法来执行此操作,或者是否有一些我没有找到的类,或者是否有更好的方法来解决我的问题?

对于上下文,我从 x509.Certificate 中获得了 rsa.PublicKey,它来自 yubikey,证明其 PIV 插槽之一中的 key 。

最佳答案

NewPublicKey来自 crypto/ssh 包的函数 http://godoc.org/golang.org/x/crypto/ssh#NewPublicKey可以拿*rsa.PublicKey作为参数并返回 PublicKey 的一个实例包含 Verify 的界面方法 ( Verify(data []byte, sig *Signature) error ) - http://godoc.org/golang.org/x/crypto/ssh#PublicKey .

下面的程序说明了这一点——我们创建一个新的 *rsa.PrivateKey 并用它签署一条消息,然后转换 *rsa.PublicKeyssh.PublicKey使用 NewPublicKey函数并验证签名;如果原始数据被修改,还要检查签名验证是否失败。为简洁起见,省略了错误检查。

package mainimport (    "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\n")    // 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")    }}

输出:

Signature OK

关于go - 将 rsa.PublicKey 转换为 ssh.PublicKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38579982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com