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

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题