doupang5433 2014-07-15 12:06
浏览 534
已采纳

Golang:将字节数组转换为big.Int

I'm trying to create an RSA Public Key from a Modulus and Exponent stored in a byte array. After some experimentation I've got the following:

func bytes_to_int(b []byte) (acc uint64) {
  length := len(b)
  if length % 4 != 0 {
    extra := (4 - length % 4)
    b = append([]byte(strings.Repeat("\000", extra)), b...)
    length += extra
  }
  var block uint32
  for i := 0; i < length; i += 4 {
    block = binary.BigEndian.Uint32(b[i:i+4])
    acc = (acc << 32) + uint64(block)
  }
return
}

func main() {
  fmt.Println(bytes_to_int(data[:128]))
  fmt.Println(bytes_to_int(data[128:]))
}

This appears to work (although I'm not convinced there isn't a better way). My next step was to convert it to use math/big in order to handle larger numbers. I can see an Lsh function to do the << but can't figure out how to recursively add the Uint32(block) to the big.Int.

For reference, the Public Key I'm attempting to import is a Mixmaster Key stored in a keyring (pubring.mix): http://www.mixmin.net/draft-sassaman-mixmaster-XX.html#key-format http://pinger.mixmin.net/pubring.mix

  • 写回答

3条回答 默认 最新

  • douyi9787 2014-07-15 12:25
    关注

    You want Int.SetBytes to make a big.int from a slice of []byte.

    func (z *Int) SetBytes(buf []byte) *Int
    

    SetBytes interprets buf as the bytes of a big-endian unsigned integer, sets z to that value, and returns z.

    This should be quite straightforward to use in your application since your keys are in big-endian format according to the doc you linked.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵