doulangchao8934 2014-01-24 00:28
浏览 544
已采纳

如何在Go中存储ECDSA私钥

I am using the ecdsa.GenerateKey method to generate a private/public key pair in Go. I would like to store the private key in a file on the users computer, and load it whenever the program starts. There is a method elliptic.Marshal that marshals the public key, but nothing for the private key. Should I simply roll my own, or is there a recommended way to store the private key?

  • 写回答

3条回答 默认 最新

  • dscizpq790832708 2016-12-24 17:24
    关注

    Here is a code sample that demonstrates encoding and decoding of keys in Go. It helps to know that you need to connect couple of steps. Crypto algorithm is the fist step, in this case ECDSA key. Then you need standard encoding, x509 is most commontly used standard. Finally you need a file format, PEM is again commonly used one. This is currently most commonly used combination, but feel free to substitute any other algoriths or encoding.

    func encode(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) (string, string) {
        x509Encoded, _ := x509.MarshalECPrivateKey(privateKey)
        pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded})
    
        x509EncodedPub, _ := x509.MarshalPKIXPublicKey(publicKey)
        pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub})
    
        return string(pemEncoded), string(pemEncodedPub)
    }
    
    func decode(pemEncoded string, pemEncodedPub string) (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
        block, _ := pem.Decode([]byte(pemEncoded))
        x509Encoded := block.Bytes
        privateKey, _ := x509.ParseECPrivateKey(x509Encoded)
    
        blockPub, _ := pem.Decode([]byte(pemEncodedPub))
        x509EncodedPub := blockPub.Bytes
        genericPublicKey, _ := x509.ParsePKIXPublicKey(x509EncodedPub)
        publicKey := genericPublicKey.(*ecdsa.PublicKey)
    
        return privateKey, publicKey
    }
    
    func test() {
        privateKey, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
        publicKey := &privateKey.PublicKey
    
        encPriv, encPub := encode(privateKey, publicKey)
    
        fmt.Println(encPriv)
        fmt.Println(encPub)
    
        priv2, pub2 := decode(encPriv, encPub)
    
        if !reflect.DeepEqual(privateKey, priv2) {
            fmt.Println("Private keys do not match.")
        }
        if !reflect.DeepEqual(publicKey, pub2) {
            fmt.Println("Public keys do not match.")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝