RSA 公钥加密与签名实验
Completion requirements
所有的 BIGNUM API 都可以从 https://linux.die.net/man/3/bn 中找到。在下文中,我们介绍一下此实验所需的一些 API 。
临时变量内存:有些库函数需要临时变量,它们的内存需要动态分配。但如果每次调用时都去动态分配内存的代价很高。常用的方法是使用 BN_CTX 结构来保存库函数使用的临时变量。我们先创建这样一个结构,然后传递给需要使用它的函数。
BN_CTX *ctx = BN_CTX_new()
初始化 BIGNUM 变量:
BIGNUM *a = BN_new()
给 BIGNUM 变量赋值:
// 用 10 进制数字字符串赋值
BN_dec2bn(&a, "12345678901112231223");
// 用 16 进制数字字符串赋值
BN_hex2bn(&a, "2A3B4C55FF77889AED3F");
// 生成 128 位的随机数
BN_rand(a, 128, 0, 0);
// 生成 128 位的随机质数
BN_generate_prime_ex(a, 128, 1, NULL, NULL, NULL);
输出大整数:
void printBN(char *msg, BIGNUM * a)
{
// 把 BIGNUM 转换成 10 进制数字字符串
char * number_str = BN_bn2dec(a);
// 打印数字字符串
printf("%s %s\n", msg, number_str);
// 释放分配的内存
OPENSSL_free(number_str);
}
计算 res = a - b 和 res = a + b:
BN_sub(res, a, b);
BN_add(res, a, b);
计算 res = a * b: 注意这个 API 需要 BN_CTX。
BN_mul(res, a, b, ctx)
计算 res = a * b mod n:
BN_mod_mul(res, a, b, n, ctx)
计算 res = ac mod n:
BN_mod_exp(res, a, c, n, ctx)
计算模逆元 (modular inverse): 也就是 给定 a,找到一个 b,使得 a * b mod n = 1,b 被称为 a 模 n 的逆元。
BN_mod_inverse(b, a, n, ctx);
Last modified: Tuesday, 13 May 2025, 10:38 PM