dongleiwei2182 2018-09-25 16:09
浏览 170
已采纳

如何从PublicKey生成字节数组

I'm use crypto lib, ran into a problem: I need to convert the PublicKey type into byte[], as it can be done with a private key:

privkey.D.Bytes()

How can I solve this problem?

  • 写回答

1条回答 默认 最新

  • dongyun6229 2018-09-25 16:18
    关注

    ecdsa.PrivateKey is a struct:

    type PrivateKey struct {
            PublicKey
            D *big.Int
    }
    

    So privkey.D.Bytes() returns you the bytes of the D big integer.

    Similarly, ecdsa.PublicKey:

    type PublicKey struct {
            elliptic.Curve
            X, Y *big.Int
    }
    

    You may do the same with pubkey.X and pubkey.Y fields. These will give you 2 separate byte slices. If you need to merge them into one, you need to come up with some kind of "format", e.g. encoding the length of the first slice (the result of pubkey.X.Bytes()) using 4 bytes, then the first slice, then the length (4 bytes again) of the 2nd slice, and the second slice itself.

    Best would be to use the elliptic.Marshal() function for this:

    func Marshal(curve Curve, x, y *big.Int) []byte
    

    Marshal converts a point into the uncompressed form specified in section 4.3.6 of ANSI X9.62.

    Example using it:

    var pubkey *ecdsa.PublicKey = // ...
    
    data := elliptic.Marshal(pubkey, pubkey.X, pubkey.Y)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路