我想计算 ab mod n 以用于 RSA 解密.我的代码(如下)返回不正确的答案.有什么问题吗?
I want to calculate ab mod n for use in RSA decryption. My code (below) returns incorrect answers. What is wrong with it?
unsigned long int decrypt2(int a,int b,int n)
{
unsigned long int res = 1;
for (int i = 0; i < (b / 2); i++)
{
res *= ((a * a) % n);
res %= n;
}
if (b % n == 1)
res *=a;
res %=n;
return res;
}
你可以试试这个 C++ 代码.我已经将它用于 32 位和 64 位整数.我确定我是从 SO 那里得到的.
You can try this C++ code. I've used it with 32 and 64-bit integers. I'm sure I got this from SO.
template <typename T>
T modpow(T base, T exp, T modulus) {
base %= modulus;
T result = 1;
while (exp > 0) {
if (exp & 1) result = (result * base) % modulus;
base = (base * base) % modulus;
exp >>= 1;
}
return result;
}
你可以在 p. 的文献中找到这个算法和相关的讨论.244 的
You can find this algorithm and related discussion in the literature on p. 244 of
施奈尔,布鲁斯 (1996).应用密码学:C 语言中的协议、算法和源代码,第二版(第 2 版).威利.ISBN 978-0-471-11709-4.
Schneier, Bruce (1996). Applied Cryptography: Protocols, Algorithms, and Source Code in C, Second Edition (2nd ed.). Wiley. ISBN 978-0-471-11709-4.
<小时>
请注意,在此简化版本中,乘法 result * base 和 base * base 可能会溢出.如果模数大于 T 宽度的一半(即大于最大 T 值的平方根),则应改用合适的模乘算法 -请参阅使用原始类型进行模乘的方法的答案.
Note that the multiplications result * base and base * base are subject to overflow in this simplified version. If the modulus is more than half the width of T (i.e. more than the square root of the maximum T value), then one should use a suitable modular multiplication algorithm instead - see the answers to Ways to do modulo multiplication with primitive types.
这篇关于计算 pow(a,b) mod n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
将 RGB 转换为 HSV 并将 HSV 转换为 RGB 的算法,范围Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both(将 RGB 转换为 HSV 并将 HSV 转换为 RGB 的算法,范围为 0-255)
如何将枚举类型变量转换为字符串?How to convert an enum type variable to a string?(如何将枚举类型变量转换为字符串?)
什么时候使用内联函数,什么时候不使用?When to use inline function and when not to use it?(什么时候使用内联函数,什么时候不使用?)
C 或 C++ 中好的 goto 示例Examples of good gotos in C or C++(C 或 C++ 中好的 goto 示例)
ios_base::sync_with_stdio(false) 的意义;cin.tie(NULL);Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);(ios_base::sync_with_stdio(false) 的意义;cin.tie(NULL);)
TCHAR 仍然相关吗?Is TCHAR still relevant?(TCHAR 仍然相关吗?)