daelk-cryptography curve25519-dalek源码解析——之Field表示

2023-10-24 15:30

本文主要是介绍daelk-cryptography curve25519-dalek源码解析——之Field表示,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

https://github.com/dalek-cryptography/curve25519-dalek

1. Scalar结构

针对p<2255的域filed,采用scalar以little-endian的数组形式来表示:【对于Curve25519,其p值为 2255 - 19】

/// The `Scalar` struct holds an integer \\(s < 2\^{255} \\) which
/// represents an element of \\(\mathbb Z / \ell\\).
#[derive(Copy, Clone)]
pub struct Scalar {/// `bytes` is a little-endian byte encoding of an integer representing a scalar modulo the/// group order.////// # Invariant////// The integer representing this scalar must be bounded above by \\(2\^{255}\\), or/// equivalently the high bit of `bytes[31]` must be zero.////// This ensures that there is room for a carry bit when computing a NAF representation.//// XXX This is pub(crate) so we can write literal constants.  If const fns were stable, we could//     make the Scalar constructors const fns and use those instead.pub(crate) bytes: [u8; 32], 
}

Scalar类型中的bytes成员定义为pub(crate),表示该成员可在本crate内public可见,但对除本crate外的其它crates中不可见。

因此,对于:
x = 2238329342913194256032495932344128051776374960164957527413114840482143558222

sage: hex(2238329342913194256032495932344128051776374960164957527413114840482143
....: 558222)
'4f2d979a8f449d44442cc1b1085a552527dc21b64b413598408475d34b45a4e'
sage: len('4f2d979a8f449d44442cc1b1085a552527dc21b64b413598408475d34b45a4e'
....: )
63  //对应的 the high bit of `bytes[31]` must be zero.
/// // x = 2238329342913194256032495932344128051776374960164957527413114840482143558222/// let X: Scalar = Scalar::from_bytes_mod_order([///         0x4e, 0x5a, 0xb4, 0x34, 0x5d, 0x47, 0x08, 0x84,///         0x59, 0x13, 0xb4, 0x64, 0x1b, 0xc2, 0x7d, 0x52,///         0x52, 0xa5, 0x85, 0x10, 0x1b, 0xcc, 0x42, 0x44,///         0xd4, 0x49, 0xf4, 0xa8, 0x79, 0xd9, 0xf2, 0x04,///     ]);

2. UnpackedScalar结构

程序中默认采用的是u64_backend feature
UnpackedScalar用于代表GF(l)域,其中l=2^252 + 27742317777372353535851937790883648493

/// An `UnpackedScalar` represents an element of the field GF(l), optimized for speed.
///
/// This is a type alias for one of the scalar types in the `backend`
/// module.
#[cfg(feature = "u64_backend")]
type UnpackedScalar = backend::serial::u64::scalar::Scalar52;/// An `UnpackedScalar` represents an element of the field GF(l), optimized for speed.
///
/// This is a type alias for one of the scalar types in the `backend`
/// module.
#[cfg(feature = "u32_backend")]
type UnpackedScalar = backend::serial::u32::scalar::Scalar29;

参照libsnark中的格式const mp_size_t alt_bn128_r_limbs = (alt_bn128_r_bitcount+GMP_NUMB_BITS-1)/GMP_NUMB_BITS;,即bitcount=255:

  • 对于64位系统,数组大小的计算公式为n=roundup[(bitcount+64-1)/64]=5,为了减少计算复杂度(无需考虑所有64位,仅需关注libm位的计算操作),libm仅需用满足libm*n略大于等于bitcount,此时libm本可以取值51(51*5=255),但考虑到Montgomery multiplication reduce的需要,libm取值52。
  • 对于32位系统,数组大小的计算公式为n=roundup[(bitcount+32-1)/32]=9,同理此时libm取值29。
/// The `Scalar52` struct represents an element in
/// \\(\mathbb Z / \ell \mathbb Z\\) as 5 \\(52\\)-bit limbs.
#[derive(Copy,Clone)]
pub struct Scalar52(pub [u64; 5]);

3. Scalar与UnpackedScalar转换

	/// let inv_X: Scalar = X.invert();/// assert!(XINV == inv_X);/// let should_be_one: Scalar = &inv_X * &X;/// assert!(should_be_one == Scalar::one());/// ```pub fn invert(&self) -> Scalar {self.unpack().invert().pack()}/// Unpack this `Scalar` to an `UnpackedScalar` for faster arithmetic.pub(crate) fn unpack(&self) -> UnpackedScalar {UnpackedScalar::from_bytes(&self.bytes)}

3.1 Scalar转换为UnpackedScalar

Scalar转换为UnpackedScalar的代码细节为:

	/// Unpack a 32 byte / 256 bit scalar into 5 52-bit limbs.pub fn from_bytes(bytes: &[u8; 32]) -> Scalar52 {let mut words = [0u64; 4];for i in 0..4 {for j in 0..8 {words[i] |= (bytes[(i * 8) + j] as u64) << (j * 8);}}let mask = (1u64 << 52) - 1; //仅取52bitlet top_mask = (1u64 << 48) - 1; //仅取48bitlet mut s = Scalar52::zero();// 一共仅保留256bit,words数组中是将scalar值按64bit为单位分别存储// 以下是要以52bit单位分别存储到s数组中,需要对words中的内容进行移位及mask处理,s数组内一共存储256bit有效位数。s[ 0] =   words[0]                            & mask; s[ 1] = ((words[0] >> 52) | (words[1] << 12)) & mask;s[ 2] = ((words[1] >> 40) | (words[2] << 24)) & mask;s[ 3] = ((words[2] >> 28) | (words[3] << 36)) & mask;s[ 4] =  (words[3] >> 16)                     & top_mask;s}

3.2 invert()操作

有限域内的乘法具有以下特征:

x(p-2) * x = x(p-1) = 1 (mod p)

由此可推测出,求有限域的x值的倒数可转换为求x(p-2)的值。

程序中,对Scalar值求倒数,是先通过unpack()函数将Scalar转换为UnpackedScalar,然后对UnpackedScalar求倒数,最后通过pack()函数将UnpackedScalar转换为Scalar值。

impl Scalar {/// let inv_X: Scalar = X.invert();/// assert!(XINV == inv_X);/// let should_be_one: Scalar = &inv_X * &X;/// assert!(should_be_one == Scalar::one());/// ```pub fn invert(&self) -> Scalar {self.unpack().invert().pack()}/// Unpack this `Scalar` to an `UnpackedScalar` for faster arithmetic.pub(crate) fn unpack(&self) -> UnpackedScalar {UnpackedScalar::from_bytes(&self.bytes)}
}impl UnpackedScalar {/// Inverts an UnpackedScalar not in Montgomery form.pub fn invert(&self) -> UnpackedScalar {self.to_montgomery().montgomery_invert().from_montgomery()}/// Pack the limbs of this `UnpackedScalar` into a `Scalar`.fn pack(&self) -> Scalar {Scalar{ bytes: self.to_bytes() }}
}

对于u64_backend feature, 有 type UnpackedScalar = backend::serial::u64::scalar::Scalar52;,所以对于
to_montgomery()的具体实现如下:

impl Scalar52 {/// Puts a Scalar52 in to Montgomery form, i.e. computes `a*R (mod l)`#[inline(never)]pub fn to_montgomery(&self) -> Scalar52 {Scalar52::montgomery_mul(self, &constants::RR) //将数组中52*5=260,260bit所有位数都用上。pub struct Scalar52(pub [u64; 5]);}/// Compute `(a * b) / R` (mod l), where R is the Montgomery modulus 2^260#[inline(never)]pub fn montgomery_mul(a: &Scalar52, b: &Scalar52) -> Scalar52 {Scalar52::montgomery_reduce(&Scalar52::mul_internal(a, b))}/// Compute `a * b`#[inline(always)]pub (crate) fn mul_internal(a: &Scalar52, b: &Scalar52) -> [u128; 9] {let mut z = [0u128; 9];z[0] = m(a[0],b[0]);z[1] = m(a[0],b[1]) + m(a[1],b[0]);z[2] = m(a[0],b[2]) + m(a[1],b[1]) + m(a[2],b[0]);z[3] = m(a[0],b[3]) + m(a[1],b[2]) + m(a[2],b[1]) + m(a[3],b[0]);z[4] = m(a[0],b[4]) + m(a[1],b[3]) + m(a[2],b[2]) + m(a[3],b[1]) + m(a[4],b[0]);z[5] =                m(a[1],b[4]) + m(a[2],b[3]) + m(a[3],b[2]) + m(a[4],b[1]);z[6] =                               m(a[2],b[4]) + m(a[3],b[3]) + m(a[4],b[2]);z[7] =                                              m(a[3],b[4]) + m(a[4],b[3]);z[8] =                                                             m(a[4],b[4]);z}/// u64 * u64 = u128 multiply helper#[inline(always)]fn m(x: u64, y: u64) -> u128 {(x as u128) * (y as u128)}/// Compute `limbs/R` (mod l), where R is the Montgomery modulus 2^260#[inline(always)]pub (crate) fn montgomery_reduce(limbs: &[u128; 9]) -> Scalar52 {#[inline(always)]fn part1(sum: u128) -> (u128, u64) {let p = (sum as u64).wrapping_mul(constants::LFACTOR) & ((1u64 << 52) - 1);((sum + m(p,constants::L[0])) >> 52, p)}#[inline(always)]fn part2(sum: u128) -> (u128, u64) {let w = (sum as u64) & ((1u64 << 52) - 1);(sum >> 52, w)}// note: l3 is zero, so its multiplies can be skippedlet l = &constants::L;// the first half computes the Montgomery adjustment factor n, and begins adding n*l to make limbs divisible by Rlet (carry, n0) = part1(        limbs[0]);let (carry, n1) = part1(carry + limbs[1] + m(n0,l[1]));let (carry, n2) = part1(carry + limbs[2] + m(n0,l[2]) + m(n1,l[1]));let (carry, n3) = part1(carry + limbs[3]              + m(n1,l[2]) + m(n2,l[1]));let (carry, n4) = part1(carry + limbs[4] + m(n0,l[4])              + m(n2,l[2]) + m(n3,l[1]));// limbs is divisible by R now, so we can divide by R by simply storing the upper half as the resultlet (carry, r0) = part2(carry + limbs[5]              + m(n1,l[4])              + m(n3,l[2]) + m(n4,l[1]));let (carry, r1) = part2(carry + limbs[6]                           + m(n2,l[4])              + m(n4,l[2]));let (carry, r2) = part2(carry + limbs[7]                                        + m(n3,l[4])             );let (carry, r3) = part2(carry + limbs[8]                                                     + m(n4,l[4]));let         r4 = carry as u64;// result may be >= l, so attempt to subtract lScalar52::sub(&Scalar52([r0,r1,r2,r3,r4]), l)}
}

4. constant.rs中常量值sage验证

/// constant.rs中有记录一些常量值。
/// `L` is the order of base point, i.e. 2^252 + 27742317777372353535851937790883648493
pub(crate) const L: Scalar52 = Scalar52([ 0x0002631a5cf5d3ed, 0x000dea2f79cd6581, 0x000000000014def9, 0x0000000000000000, 0x0000100000000000 ]);/// 其实即为L[0]*LFACTOR = -1 (mod 2^52) = 2^52-1 (mod 2^52)
/// (L[i]<<52)*LFACTOR = 0 (mod 2^52) 其中 1 =< i <= 4
/// `L` * `LFACTOR` = -1 (mod 2^52)
pub(crate) const LFACTOR: u64 = 0x51da312547e1b;/// `R` = R % L where R = 2^260
pub(crate) const R: Scalar52 = Scalar52([ 0x000f48bd6721e6ed, 0x0003bab5ac67e45a, 0x000fffffeb35e51b, 0x000fffffffffffff, 0x00000fffffffffff ]);/// `RR` = (R^2) % L where R = 2^260
pub(crate) const RR: Scalar52 = Scalar52([ 0x0009d265e952d13b, 0x000d63c715bea69f, 0x0005be65cb687604, 0x0003dceec73d217f, 0x000009411b7c309a ]);

对应的sage验证为:

sage: 2^252 + 27742317777372353535851937790883648493
7237005577332262213973186563042994240857116359379907606001950938285454250989
sage: is_prime(72370055773322622139731865630429942408571163593799076060019509382
....: 85454250989)
True
sage: hex(7237005577332262213973186563042994240857116359379907606001950938285454
....: 250989)
'1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'  //即pub(crate) const L: Scalar52为数组内每个元素只截取13个数字(52bit),按little-endian方式存储。sage: L=2^252 + 27742317777372353535851937790883648493
sage: LFACTOR=0x51da312547e1b
sage: LFACTOR
1439961107955227
sage: mod(L*LFACTOR, 2^52)  //即`L` * `LFACTOR` = -1 (mod 2^52)
4503599627370495
sage: 2^52
4503599627370496sage: R=2^260
sage: mod(R,L)
7237005577332262213973186563042994233755083008372585100823854863819240236781
sage: hex(7237005577332262213973186563042994233755083008372585100823854863819240
....: 236781)
'fffffffffffffffffffffffffffffeb35e51b3bab5ac67e45af48bd6721e6ed' //即pub(crate) const R: Scalar52为数组内每个元素只截取13个数字(52bit),按little-endian方式存储。sage: mod(R^2, L)
4185850391763183796333492317919282507600454137915443218209456916606550724923
sage: hex(4185850391763183796333492317919282507600454137915443218209456916606550
....: 724923)
'9411b7c309a3dceec73d217f5be65cb687604d63c715bea69f9d265e952d13b'
sage:sage: gcd(L,R) //符合Montgomery reduction定义的条件。可参见https://blog.csdn.net/mutourend/article/details/95613967 第2.4.1节内容
1

5. 生成程序帮助文档

/////!格式表示的注释,在以cargo doc命令运行会在target/doc目录下生成相应的.html帮助文档。
在这里插入图片描述

参考资料:
[1] https://stackoverflow.com/questions/41666235/how-do-i-make-an-rust-item-public-within-a-crate-but-private-outside-it

这篇关于daelk-cryptography curve25519-dalek源码解析——之Field表示的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/276094

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解