[英]How to calculate modular multplication of array elements to integers in c?
Consider the following: 考虑以下:
uint8_t message[15] = {
0x32, 0xdc, 0x21, 0x55, 0x3f, 0x87, 0xc8, 0x1e,
0x85, 0x10, 0x43, 0xf9, 0x93, 0x34, 0x1a
};
uint64_t num = 0xa1b2c33412;
I want to multiply the above variable num
to the array message[]
. 我想将上述变量
num
乘以数组message[]
。 The pseudo-code for what I have need, is following: 我需要的伪代码如下:
uint8_t message[15] = {
0x32, 0xdc, 0x21, 0x55, 0x3f, 0x87, 0xc8, 0x1e,
0x85, 0x10, 0x43, 0xf9, 0x93, 0x34, 0x1a
};
uint64_t num = 0xa1b2c33412;
uint64_t p = 0x31ba62ca3037;
uint64_t result = 0x00;
result = moduloMultiplication(message, num, p); // (message * num) (mod p)
I am expecting the following results: 我期望得到以下结果:
num * msg = num*msg mod p
num * msg = 0x2bf2d18cdf92 (Final result)
Is there any way to multiply the array with value of type uint64_t
? 有什么方法可以将数组与
uint64_t
类型的值相乘?
Any help regarding this will be appreciated... 任何对此的帮助将不胜感激...
Assuming the number stored in the 15-byte array is in big-endian order, here is a simple solution: 假设存储在15字节数组中的数字为大端顺序,这是一个简单的解决方案:
#include <stdio.h>
#include <stdint.h>
uint64_t moduloMultiplication(const uint8_t message[15], size_t n,
uint64_t num, uint64_t p)
{
uint64_t res = 0;
for (size_t i = 0; i < n; i++) {
// assuming `p < 1ULL << 56`
res = (res * 256 + message[i] * num) % p;
}
return res;
}
int main() {
uint8_t message[15] = {
0x32, 0xdc, 0x21, 0x55, 0x3f, 0x87, 0xc8, 0x1e,
0x85, 0x10, 0x43, 0xf9, 0x93, 0x34, 0x1a
};
uint64_t num = 0xa1b2c33412;
uint64_t p = 0x31ba62ca3037;
// result = (message * num) (mod p)
uint64_t result = moduloMultiplication(message, sizeof message, num, p);
printf("%#"PRIx64"\n", result);
return 0;
}
Output: 0x2bf2d18cdf92
输出:
0x2bf2d18cdf92
The result differs from that in the question because either the message
is incorrect, or your intermediary result is approximate: 201FF4CDCFE8C0000000000000000000000000000
seems incorrect. 结果与问题中的结果不同,因为该
message
不正确,或者您的中介结果是近似的: 201FF4CDCFE8C0000000000000000000000000000
似乎不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.