我有一个程序,有点像密码学的实验。在我尝试隔离公共指数和模数时,我一直在使用上述函数。它可以工作一段时间,但是每当我执行计算足够多次时,mpz_t变量的地址就会发生变化,然后就会抛出分段错误。
// get N and e from public key of format
// {e}FFFFFFFFFFFFFFFF{N}
void get_N_e(mpz_t retvalN, mpz_t retvale, mpz_t key) {
// create 0xFF as a mpz_t to use AND on it later
mpz_t ff;
mpz_init(ff);
mpz_set_ui(ff, 0xff);
// store the huge number to be imported later
char data[4096];
// count the number of consecutive 0xFFs
int no_ffs = 0;
// index for data
long i = 0;
while (no_ffs < 8) {
// test = key & 0xFF
mpz_t test;
mpz_init(test);
mpz_set_ui(test, 0);
mpz_and(test, key, ff);
// tmp = (unsigned int) test
unsigned int tmp;
tmp = mpz_get_ui(test);
mpz_clear(test);
if (tmp == 0xff) {
++no_ffs;
}
else {
data[i++] = tmp;
no_ffs = 0;
}
// key >>= 8
// source of the segfault
mpz_tdiv_q_2exp(key, key, 8);
}
mpz_clear(ff);
mpz_import(retvalN, 4096, 1, sizeof(char), 1, 0, data);
}
我找到了答案。事实证明,我没有检查key
是否不等于零。添加一些代码来检查解决了我的段错误问题。