curve25519-dalek中Scalar的Montgomery inversion及batch_invert算法

智慧市政灯联网解决方案.pptx 立即下载

根据资料【1】中定义,
The Montgomery inverse of an integer a ∈ [1, p−1] is defined by Kaliski [3] as the integer x=a−12n(mod p)x = a^{−1}2^n (mod\ p)x=a−12n(mod p). Similarly,
we will use the notation
x:=MonInv(a)=a−12n(mod p)x := MonInv(a) = a^{−1}2^n (mod\ p)x:=MonInv(a)=a−12n(mod p)

1. Montgomery inverse

取R=2n,若需求a的倒数x,使得ax = 1 mod p,则有

1)计算 b = aR2。
2)计算montgomery reduction of b:
c = bR-1 mod p = (aR2)R-1 mod p = aR mod p
3)计算montgomery inversion of c:
x:= MonInv© = c-1R mod p = (aR)-1R mod p = a-1 mod p.

根据步骤3),则可获得a的倒数x,使得ax = 1 mod p。

2. 有限域内倒数

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

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

由此可推测出,求有限域的x值的倒数可转换为求x(p-2)的值。求p-2次幂的运算可基于理论基础为 https://briansmith.org/ecc-inversion-addition-chains-01#curve25519_scalar_inversion 。

3. 实际代码实现

https://github.com/dalek-cryptography/curve25519-dalek/blob/a659b92305cd3286be270cba39e1ae7c8cf59b73/src/scalar.rs 的具体实现如下 :
其中步骤1)和2)对应to_montgomery()函数实现;
步骤3)对应montgomery_invert()和from_montgomery()函数实现。

实际to_montgomery()中针对输入值a,求解的是:
c=(aR2)R-1 mod p = aR mod p.

实际montgomery_invert()中针对输入值c=aR mod p,求解的是:
y = c(p-2)R-(p-3) mod p = (cR-1)(p-2)R mod p = (cR-1)-1R mod p = R2/c mod p.

实际from_montgomery()输入的为y,求解的是:
x = yR-1 mod p = (cR-1)-1 mod p = a-1 mod p.

由此,x即为a的mod p 倒数。
ax=1 mod p.

/// Inverts an UnpackedScalar not in Montgomery form.
   pub fn invert(&self) -> UnpackedScalar {
       self.to_montgomery().montgomery_invert().from_montgomery()
   }
   
    /// 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)
   }
    /// Takes a Scalar52 out of Montgomery form, i.e. computes `a/R (mod l)`
   #[inline(never)]
   pub fn from_montgomery(&self) -> Scalar52 {
       let mut limbs = [0u128; 9];
       for i in 0..5 {
           limbs[i] = self[i] as u128;
       }
       Scalar52::montgomery_reduce(&limbs)
   }
   
// 针对步骤3):
/// Inverts an UnpackedScalar in Montgomery form.
   pub fn montgomery_invert(&self) -> UnpackedScalar {
       // Uses the addition chain from
       // https://briansmith.org/ecc-inversion-addition-chains-01#curve25519_scalar_inversion
       let    _1 = self;
       let   _10 = _1.montgomery_square();
       let  _100 = _10.montgomery_square();
       let   _11 = UnpackedScalar::montgomery_mul(&_10,     &_1);
       let  _101 = UnpackedScalar::montgomery_mul(&_10,    &_11);
       let  _111 = UnpackedScalar::montgomery_mul(&_10,   &_101);
       let _1001 = UnpackedScalar::montgomery_mul(&_10,   &_111);
       let _1011 = UnpackedScalar::montgomery_mul(&_10,  &_1001);
       let _1111 = UnpackedScalar::montgomery_mul(&_100, &_1011);

       // _10000
       let mut y = UnpackedScalar::montgomery_mul(&_1111, &_1);

       #[inline]
       fn square_multiply(y: &mut UnpackedScalar, squarings: usize, x: &UnpackedScalar) {
           for _ in 0..squarings {
               *y = y.montgomery_square();
           }
           *y = UnpackedScalar::montgomery_mul(y, x);
       }

       square_multiply(&mut y, 123 + 3, &_101);
       square_multiply(&mut y,   2 + 2, &_11);
       square_multiply(&mut y,   1 + 4, &_1111);
       square_multiply(&mut y,   1 + 4, &_1111);
       square_multiply(&mut y,       4, &_1001);
       square_multiply(&mut y,       2, &_11);
       square_multiply(&mut y,   1 + 4, &_1111);
       square_multiply(&mut y,   1 + 3, &_101);
       square_multiply(&mut y,   3 + 3, &_101);
       square_multiply(&mut y,       3, &_111);
       square_multiply(&mut y,   1 + 4, &_1111);
       square_multiply(&mut y,   2 + 3, &_111);
       square_multiply(&mut y,   2 + 2, &_11);
       square_multiply(&mut y,   1 + 4, &_1011);
       square_multiply(&mut y,   2 + 4, &_1011);
       square_multiply(&mut y,   6 + 4, &_1001);
       square_multiply(&mut y,   2 + 2, &_11);
       square_multiply(&mut y,   3 + 2, &_11);
       square_multiply(&mut y,   3 + 2, &_11);
       square_multiply(&mut y,   1 + 4, &_1001);
       square_multiply(&mut y,   1 + 3, &_111);
       square_multiply(&mut y,   2 + 4, &_1111);
       square_multiply(&mut y,   1 + 4, &_1011);
       square_multiply(&mut y,       3, &_101);
       square_multiply(&mut y,   2 + 4, &_1111);
       square_multiply(&mut y,       3, &_101);
       square_multiply(&mut y,   1 + 2, &_11);

       y
   }

4. batch_invert算法

 // 本算法要求inputs中所有元素值均为非零。其中返回值为Scalar类型为inputs所有成员乘积的倒数。
 // 输入inputs值为mut,返回时其中存储的为每个成员相应的倒数。
#[cfg(feature = "alloc")]
    pub fn batch_invert(inputs: &mut [Scalar]) -> Scalar {
        // This code is essentially identical to the FieldElement
        // implementation, and is documented there.  Unfortunately,
        // it's not easy to write it generically, since here we want
        // to use `UnpackedScalar`s internally, and `Scalar`s
        // externally, but there's no corresponding distinction for
        // field elements.

        use clear_on_drop::ClearOnDrop;
        use clear_on_drop::clear::ZeroSafe;
        // Mark UnpackedScalars as zeroable.
        unsafe impl ZeroSafe for UnpackedScalar {}

        let n = inputs.len();
        let one: UnpackedScalar = Scalar::one().unpack().to_montgomery(); //为R mod p

        // Wrap the scratch storage in a ClearOnDrop to wipe it when
        // we pass out of scope.
        let scratch_vec = vec![one; n];
        let mut scratch = ClearOnDrop::new(scratch_vec);

        // Keep an accumulator of all of the previous products
        let mut acc = Scalar::one().unpack().to_montgomery(); //为R mod p

        // Pass through the input vector, recording the previous
        // products in the scratch space //假设inputs=[x_0,x_1,...x_(n-1)]
        for (input, scratch) in inputs.iter_mut().zip(scratch.iter_mut()) { //从0~n-1
            *scratch = acc; //即为x_0=R mod p, scratch_i=x_(i-1)*x_(i-2)*...*x_1*x_0*R mod p

            // Avoid unnecessary Montgomery multiplication in second pass by
            // keeping inputs in Montgomery form
            let tmp = input.unpack().to_montgomery(); //即为tmp=x_i*R mod p
            *input = tmp.pack(); // x_i = x_i*R mod p
            acc = UnpackedScalar::montgomery_mul(&acc, &tmp); // 即为acc= R*x_0*x_1....*x_(n-1)*R/R mod p = x_0*x_1....*x_(n-1)*R mod p
        }

        // acc is nonzero iff all inputs are nonzero
        debug_assert!(acc.pack() != Scalar::zero()); //本算法要求inputs中所有元素值均为非零。

        // Compute the inverse of all products
        acc = acc.montgomery_invert().from_montgomery(); //即为acc=R^2/acc/R mod p = R/acc mod p = 1/(x_0*x_1....*x_(n-1)) mod p

        // We need to return the product of all inverses later
        let ret = acc.pack(); // 即为ret = 1/(x_0*x_1....*x_(n-1)) mod p

        // Pass through the vector backwards to compute the inverses
        // in place
        for (input, scratch) in inputs.iter_mut().rev().zip(scratch.into_iter().rev()) { //注意此处,从n-1~0,以下先以i=n-1为例,其他同理。
            let tmp = UnpackedScalar::montgomery_mul(&acc, &input.unpack()); //即为tmp = acc*x_(n-1)*R/R mod p = 1/(x_0*x_1....*x_(n-2)) mod p
            *input = UnpackedScalar::montgomery_mul(&acc, &scratch).pack(); // 即为x_(n-1) = acc*x_(n-2)*x_(n-3)*...*x_1*x_0*R/R mod p = 1/x_(n-1)
            acc = tmp; //即为acc = 1/(x_0*x_1....*x_(n-2)) mod p
        }

        ret
    }

参考资料:
[1] http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.75.8377&rep=rep1&type=pdf
[2] https://briansmith.org/ecc-inversion-addition-chains-01#curve25519_scalar_inversion
[3] https://briansmith.org/ecc-inversion-addition-chains-01#curve25519_scalar_inversion
[4] https://github.com/dalek-cryptography/curve25519-dalek/blob/a659b92305cd3286be270cba39e1ae7c8cf59b73/src/scalar.rs

【负荷频率和电压控制】电力系统的组合负荷频率和电压控制模型研究(Simulink) 内容概要:本文针对电力系统中频率与电压耦合控制的关键问题,研究了组合负荷频率控制(LFC)与自动电压调节(AVR)的协同建模方法,基于Simulink搭建动态仿真系统,构建了能够反映负载突变、发电侧扰动等实际工况的多变量控制系统模型。通过集成经典控制理论与现代仿真技术,设计协调控制器以同时稳定系统频率和关键母线电压,有效抑制因功率不平衡引发的动态波动,提升电力系统的整体稳定性与电能质量。文中详述了系统建模流程、控制策略设计原理及仿真验证过程,为复杂电力系统的多目标协同控制提供了理论依据与实践参考。; 适合人群:电力系统自动化、电气工程及其相关专业的高校研究生、科研机构研究人员以及从事电网运行、控制策略开发的工程技术从业人员。; 使用场景及目标:①用于深入理解负荷频率控制与电压调节之间的动态耦合机制及其交互影响;②为含高比例新能源接入的现代电力系统提供频率-电压协同控制的仿真验证平台;③支撑PID、模糊逻辑、最优控制等先进控制算法在多输入多输出(MIMO)电力系统稳定控制中的研究与应用。; 阅读建议:建议结合提供的Simulink模型文件进行同步操作学习,重点掌握控制器结构设计与参数整定方法,关注系统在不同扰动工况下的动态响应特性,并可进一步拓展研究新能源出力不确定性、负荷随机性对控制性能的影响。 立即下载

相关推荐

Linux虚拟机mysql安装教程(详细步骤)出现了一个错误:依赖检测失败

Linux虚拟机安装mysql的详细步骤(有报错预警哦)

m0_74953387的博客 5263

python 实现求模逆算法

求模逆算法是数论和密码学中一个重要的概念,用于在模运算下找到某个数的乘法逆元。乘法逆元是指一个数,与该数相乘后在模某个给定数的情况下结果为1。

luthane的博客 1239

hcaptcha无感验证码逆向实战:从接口分析到环境补全

本文详细解析了hcaptcha无感验证码的逆向实战过程。通过分析核心接口与加密逻辑,重点介绍了采用环境补全策略来模拟真实浏览器环境,从而绕过验证码检测。文章提供了从接口抓包、剖析hsw.js加密核心到使用Node.js搭建模拟环境的完整步骤,为自动化操作提供了一种稳健的解决方案。

weixin_29324401的博客 1167

【日记】Montgomery Modular Inverse

(r, k) = AlmMonInv(a, m) = (a^-1)(2 ^k) (mod m) /// <summary> /// 返回{x, k};x = <paramref name="value"/>−1 * 2^k (mod <paramref name="modulo"/>) /// if gcd(<paramref name="value...

我是个SHA手灬莫得感情的博客 316

海思HiMPP开发避坑指南:MMZ内存与系统内存傻傻分不清?一个例子讲透

本文深入解析海思HiMPP开发中MMZ内存与系统内存的关键差异与应用场景,帮助开发者避免常见的内存混淆问题。通过实际案例和性能对比,详细介绍了MMZ内存的特性和优化策略,提升多媒体处理效率。

weixin_30772105的博客 473

RK3588内核崩溃日志捕获:pstore与ramoops的实战配置指南

本文详细介绍了在RK3588嵌入式设备上配置pstore与ramoops以捕获内核崩溃日志的实战指南。通过内核配置调整、设备树设置及高级调试技巧,帮助开发者有效定位系统崩溃原因,特别适合户外智能设备等无法长期连接调试器的场景。文章还提供了生产环境优化建议,确保日志捕获的可靠性与安全性。

weixin_29189363的博客 414

MbedTLS中的Montgomery算法实现解析(一)

MbedTLS中的Montgomery算法实现解析(一) 蒙哥马利算法模乘介绍 蒙哥马利模乘算法主要是为了进行大数运算a×b mod n,并且针对CPU进行了并行优化,来快速计算模乘。 在介绍蒙哥马利模乘之前,先让我们来了解蒙哥马利约减(Montgomery reduction) 蒙哥马利约减(Montgomery reduction) 首先,让我们来考虑一个简单的问题: a mod n 如果a是一个2048位的整数,n是一个1024位的整数,那我们要如何来计算结果呢? 如果我们直接采用相除的方式,不论在时

qq_43324702的博客 1619

Catia二次开发QueryInterface的操蛋问题

探索了很久,尝试录制宏,打开部件属性窗口,然后随意设置一些属性(必须改变一些东西才能录制成功,否则不会录制到任何东西),再看录制的结果,发现原来CATIAAnalyze是从Product那里来的。例如获得一个部件的体积,找到相关接口CATIAAnalyze,但是这个部件的CATIAAnalyze的对象不知道如何获取。总结一下,写Catia二开代码,就像漂亮国那款《莫里秀》 又名《爸爸死哪了》的综艺节目,大部分时间都是在找爸爸!Catia二开很痛苦,明明已经找到接口类,但是却不知道怎么获得这个接口类的对象。

gergul的专栏 749

【NumPy】深入解析numpy中的invert方法

然而,随着数据规模的不断增大和计算需求的不断提升,我们还需要不断探索和优化位取反运算的性能和扩展性。位取反运算是一种基本的二进制运算,它将二进制数的每一位都取反,即0变为1,1变为0。我坚信知识的力量,希望通过我的分享,能够帮助更多的人掌握这些技术,并在实际项目中发挥作用。通过对数据的每一位进行取反运算,我们可以得到一个唯一的校验值,用于在接收端验证数据的完整性。NumPy,作为Python中用于处理大型多维数组和矩阵运算的库,其高效的运算性能和丰富的函数功能一直深受开发者和数据分析师的喜爱。

2402_83361138的博客 1391

基于DNN神经网络的多输入多输出数据回归预测(附带Matlab代码)

假设我们的输入数据包含n个特征,输出数据包含m个特征。在本文中,我们将介绍如何使用DNN(深度神经网络)实现多输入多输出数据回归预测,并提供相应的Matlab代码。需要注意的是,上述代码中的DNN模型是一个简化的示例,您可以根据实际任务的复杂程度和要求进行相应的调整和优化。综上所述,我们介绍了如何使用DNN神经网络实现多输入多输出数据回归预测,并提供了相应的Matlab代码。函数对DNN模型进行训练,其中输入数据需要转置,以适应网络的输入要求。最后,我们使用训练好的模型对测试数据进行预测,并打印预测结果。

DevWizard的博客 1073

R语言层次聚类(hierarchical clustering):数据缩放、PCA聚类结果可视化、fpc包的clusterboot函数通过bootstrap重采样的方法评估hclust层次聚类的稳定性

R语言层次聚类(hierarchical clustering):数据缩放、PCA聚类结果可视化、fpc包的clusterboot函数通过bootstrap重采样的方法评估hclust层次聚类的稳定性

data+scenario+science+insight 841

利用sklearn进行数据归一化

利用sklearn进行数据归一化 1. from sklearn.preprocessing import MinMaxScaler data = [[-1,2],[-0.5,6],[0,10],[1,18]] #生成的是4*2的矩阵 import pandas as pd data = pd.DataFrame(data) print(data) print(data.shape) ...

weixin_40264772的博客 1319

任务混部最少服务器数量计算问题

这里的并行度指的是该任务运行时会占用的服务器数量。要注意的是,一个服务器在每个时刻可以被任意任务使用,但同一时刻最多只能被一个任务占用,并且任务运行结束后会立即释放服务器(结束时刻不占用)。最后,我们从字典中找出服务器数量的最大值,这个最大值就是完成这批任务混部最少需要的服务器数量。对于每个任务,我们会遍历其对应的时间区间,将该任务的并行度累加到对应时刻的服务器数量上。任务混部的目标是让这批任务由同一批服务器承载运行,你需要计算完成这批任务混部最少需要多少服务器,以此来最大化控制资源成本。

m0_62153576的博客 109

系统程序员成长计划-容器与算法(二)(下)

系统程序员成长计划-容器与算法(二)(下) 转载时请注明出处和作者联系方式文章出处:http://www.limodev.cn/blog作者联系方式:李先静 这个反序函数的原理很简单,有的读者很快就写出来了:Ret invert(LinearContainer* linear_container){ int i = 0; int j = 0; void*

国产开源 GUI 引擎 AWTK 3026

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

curve25519-dalek中field域内和scalar域内的运算性能对比

通过修改lib.rs文件,将field和backendmodule改为pub。 通过性能对比发现在curve25519-dalek库的代码实现,实际field域内计算速度优于scalar域内的计算性能。 针对field域内的加减乘除和scalar域内的加减乘除运算对应的bench代码如下: mod scalar_benches { use super::*; fn scalar_...

mutourend2010@gmail.com 398

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

CRC16常见几个标准的算法及C语言实现

CRC16常见的标准有以下几种,被用在各个规范中,其算法原理基本一致,就是在数据的输入和输出有所差异,下边把这些标准的差异列出,并给出C语言的算法实现。 CRC16_CCITT:多项式x16+x12+x5+1(0x1021),初始值0x0000,低位在前,高位在后,结果与0x0000异或 CRC16_CCITT_FALSE:多项式x16+x12+x5+1(0x1021),初始值0xFFFF,低...

leumber的专栏 10万+

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Curve25519 Field域2^255-19内的快速运算

1. 引言 对于Curve25519,其Field域内的module Fp = 2255-19。 若采用常规的Montgomery reduce算法,其运算性能并不是最优的。 如要求某整数 u mod (2^255-19),可将m整数用多项式做如下表示: u=∑iuixi,其中,ui=n∗2⌈25.5i⌉,n∈Nu=\sum_{i}^{}u_ix^i,其中,u_i=n*2^{\left \lce...

mutourend2010@gmail.com 1897

Matrix类中Invert()的用法

昨天在编程过程中,使用到了一个新的类Matrix中的一个方法Invert()。 以前没见过,单词也没印象,所以我就查找资料,结果发现这居然是一个矩阵,但是我发现例子中Matrix的构造函数是: Matrix m = new Matrix(1, 2, 3, 4, 0, 0); 但是构造函数的解释是Encapsulates a 3-by-3 affine matrix that re

茄克不爱说话 9840

求模(mod)运算的应用

1、mod运算的性质 结合律 ((a+b) mod p + c)mod p = (a + (b+c) mod p) mod p ((a*b) mod p * c)mod p = (a * (b*c) mod p) mod p 交换律 (a + b) mod p = (b+a) mod p (a × b) mod

yutianxin123的专栏 1万+

关于RSA运算的计算机计算讨论!

前言俺曾经查阅了网上找得到的各种用于实现RSA 的大数运算库,然而最终还是决定自己动手写一个。因为凡是效率高速度快的代码(crypto++、miracl、freelip、rsaref等),要么使用的数据结构过于复杂,要么编码风格杂乱无章,俺的水平和耐心都实在是有限,以至于无法读懂这些东西。而俺读得懂的一些代码,其实现方式却又过于幼稚,效率极低速度一塌糊涂。俺觉得像俺这样的人不在少数,于是决心写一个

realduke2000的专栏 3680

【算法学习笔记】-动态规划

动态规划应用于子问题重叠的情况,即不同的子问题具有公共的子子问题(子问题的求解是递归进行的,将其划分为更小的子子问题)。在这种情况下,分治法会做许多不必要的工作,它会反复地求解那些公共子子问题。而动态规划算法对每个子子问题只求解一次,将其解保存在一个表格中,从而无需每次求解一个子子问题时都重新计算,避免了这种不必要的计算工作。 我们通常按如下4个步骤来设计一个动态规划算法: 1.刻画一个最优解

Kevin_zhai的博客 1962

Python:Numpy库中的invert()函数的用法

Numpy库中的invert()函数的用法 官方解释: Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. For signe...

Sarah的博客 1万+

算法系列——二叉树翻转(Invert Binary Tree)

Invert a binary tree.

BridgeGeorge 611

质数初步

模p运算 给定一个正整数p,任意一个整数n,一定存在等式 n = kp + r 其中k、r是整数,且 0 ≤ r < p,称呼k为n除以p的商,r为n除以p的余数。 对于正整数p和整数a,b,定义如下运算: 取模运算:a mod p 表示a除以p的余数。 模p加法:(a + b) mod p ,其结果是a+b算术和除以p的余数,也就是说,(a+b...

weixin_33724570的博客 370

算法:Invert Binary Tree(翻转二叉树)

说明 算法:Invert Binary Tree LeetCode地址:https://leetcode.com/problems/invert-binary-tree/ 题目: Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / ...

AI架构师易筋 1264
上一篇: curve25519-dalek中的montgomery_reduce算法细节
下一篇: curve25519-dalek中的Scalar模运算mul/sub/add/div
mutourend
博客等级 码龄19年 3208粉丝 1222原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值