当前位置: 首页 > news >正文

Go语言-big.Int

文章目录

    • Go 语言 big.Int
    • 应用场景:大整数位运算
    • 使用举例: go sdk中crypto/ecdsa 椭圆曲线生成私钥相关结构中就有使用

Go 语言 big.Int

Go 语言 big.Int
参考URL: https://blog.csdn.net/wzygis/article/details/82867793

math/big 作为 Go 语言提供的进行大数操作的官方库。

big.Int 用于表示 大整数。

应用场景:大整数位运算

在密码学、加密算法或者需要处理大数字的领域中,使用大整数进行位操作是非常常见的。

实战demo:来自cosmos的 bip39.go

  ...// Break entropy up into sentenceLength chunks of 11 bits// For each word AND mask the rightmost 11 bits and find the word at that index// Then bitshift entropy 11 bits right and repeat// Add to the last empty slot so we can work with LSBs instead of MSB// Entropy as an int so we can bitmask without worrying about bytes slicesentropyInt := new(big.Int).SetBytes(entropy)// Slice to hold words inwords := make([]string, sentenceLength)// Throw away big int for AND maskingword := big.NewInt(0)for i := sentenceLength - 1; i >= 0; i-- {// Get 11 right most bits and bitshift 11 to the right for next timeword.And(entropyInt, Last11BitsMask)entropyInt.Div(entropyInt, RightShift11BitsDivider)// Get the bytes representing the 11 bits as a 2 byte slicewordBytes := padByteSlice(word.Bytes(), 2)// Convert bytes to an index and add that word to the listwords[i] = WordList[binary.BigEndian.Uint16(wordBytes)]}return strings.Join(words, " "), nil
}

代码解析:

entropyInt := new(big.Int).SetBytes(entropy) 这行代码的作用是将字节切片 entropy 转换为大整数。

将这些字节数据转换为大整数可以方便进行位操作、数学运算等操作,同时也能保持精度和范围。因此,将字节转换为大整数是一种常见的做法

  • 将熵(entropy)分成长度为 sentenceLength 的 11 位比特。
  • 对于每个单词,将最右边的 11 位进行按位与(AND)运算,并找到该索引位置的单词。
  • 然后将熵向右移动 11 位,重复上述操作。

使用举例: go sdk中crypto/ecdsa 椭圆曲线生成私钥相关结构中就有使用

举例:
比如 go sdk中crypto/ecdsa 椭圆曲线生成私钥相关结构中就有使用到,demo如下:
key, err := ecdsa.GenerateKey(secp256k1.S256(), seed)

// PublicKey represents an ECDSA public key.
type PublicKey struct {elliptic.CurveX, Y *big.Int
}// PrivateKey represents an ECDSA private key.
type PrivateKey struct {PublicKeyD *big.Int
}
http://www.lryc.cn/news/358199.html

相关文章:

  • getContentView(mBinding.getRoot()); 会导致内存泄露吗?里面有SurfaceView ViewBinding
  • 基于transformers框架实践Bert系列6-完形填空
  • cesium绘制编辑区域
  • 数据库攻防之MySQL
  • 八国多语言微盘微交易所系统源码 单控点控 K线完好
  • 爪哇,我初学乍道
  • 【MySQL精通之路】全文搜索(5)-限制
  • 动态规划part03 Day43
  • Activity->Activity生命周期和启动模式
  • 浅谈网络安全态势感知
  • cesium本地文档-天空盒-arcgis切片404-服务查询
  • OpenMv图片预处理
  • Springboot 实战运用
  • kafka的安装与简单使用
  • 【服务器部署篇】Linux下Node.js的安装和配置
  • 【OrangePi AIpro】香橙派 AIpro 为AI而生
  • AES算法
  • 自主创新助力科技强军,麒麟信安闪耀第九届军博会
  • Android Retrofit 封装模版
  • 【介绍下运维开发】
  • mybatis-plus中多条件查询使用and合or嵌套使用
  • 前端加密的方式汇总
  • ELT 同步 MySQL 到 Doris
  • 100个 Unity小游戏系列七 -Unity 抽奖游戏专题五 刮刮乐游戏
  • 链游:区块链技术的游戏新纪元
  • 格式化字符串
  • 错误信息:Traceback (most recent call last):
  • Thinkphp3.2.3网站后台不能访问如何修复
  • Golang 如何使用 gorm 存取带有 emoji 表情的数据
  • 计算机算法中的数字表示法——原码、反码、补码