对于大数运算,不能使用C语言基本的数据类型,而是要使用 openssl 提供的 big num library,我们将把每个大数定义为一个 BIGNUM 类型,然后使用库提供的 API 进行各种操作,如加法、乘法、求幂、模块化操作等,big number APIs可以在 https://linux.die.net/man/3/bn 找到
//ossl_typ.h structbignum_st { BN_ULONG *d; int top; int dmax; int neg; int flags; };
// bn_lcl.h typedefstructbignum_stBIGNUM;
编译命令
1
gcc cr.c -lcrypto
使用BIGNUM库进行很多位的大数操作
模意义下的幂运算
1
BN_mod_exp(res, a, c, n, ctx)
两个大数相乘
1 2
//Compute res = a ∗ b. It should be noted that a BN CTX structure is need in this API BN_mul(res, a, b, ctx)
求逆元
1 2
//Compute modular inverse, i.e., given a, find b, such that a ∗ b mod n = 1. The value b is called the inverse of a, with respect to modular n BN_mod_inverse(b, a, n, ctx)
在labPDF中,有着更多的使用范例
3.1 Task 1: Deriving the Private Key
设 p,q,e 是三个质数。设 n = p * q。我们将使用(e,n)作为公钥,请计算私钥 d。p、q 和 e 的十六进制值如下所示
1 2 3
p = F7E75FDC469067FFDC4E847C51F452DF q = E85CED54AF57E53E092113E62F436F4F e = 0D88C3
$ python -c ’print("A top secret!".encode("hex"))’
4120746f702073656372657421
给出的参数:
1 2 3 4
n = DCBFFE3E51F62E09CE7032E2677A78946A849DC4CDDE3A4D0CB81629242FB1A5 e = 010001 (this hex value equals to decimal 65537) M = A top secret! d = 74D806F9F3A62BAE331FFE3F0A68AFE35B3D2E4794148AACBC26AA381CD7D30D
M1 = I owe you $2000,对应结果为80A55421D72345AC199836F60D51DC9594E2BDB4AE20C804823FB71660DE7B82
M2 = I owe you $3000,对应结果为 04FC9C53ED7BBE4ED4BE2C24B0BDF7184B96290B4ED4E3959F58E94B1ECEA2EB
虽然明文只是改变一个字符,但是签名结果迥然不同
Task 5: Verifying a Signature
S 是 M 的签名,Alice 的公钥是(e,n),验证签名是否确实是爱丽丝的
1 2 3 4
M = Launch a missile. S = 643D6F34902D9C7EC90CB0B2BCA36C47FA37165C0005CAB026C0542CBDB6802F e = 010001 (this hex value equals to decimal 65537) n = AE1CD4DC432798D933779FBD46C6E1247F0CF1233595113AA51B450F18116115
转码得到对应hex为4c61756e63682061206d697373696c65
签名过程:私钥签名,公钥验证
与运行截图比对,$S^e$的结果与明文相同,因此签名有效
Task 6: Manually Verifying an X.509 Certificate
使用程序手动验证 X.509证书。X.509包含有关公钥的数据和数据上的发行者签名。我们将从 Web 服务器下载一个真正的 X.509证书,获取其发行者的公钥,然后使用这个公钥验证证书上的签名
证书生成过程:
首先 CA 会把持有者的公钥、用途、颁发者、有效时间等信息打成一个包,然后对这些信息进行 Hash 计算,得到一个 Hash 值;
然后 CA 会使用自己的私钥将该 Hash 值加密,生成 Certificate Signature,也就是 CA 对证书做了签名;
最后将 Certificate Signature 添加在文件证书上,形成数字证书;
Step 1: Download a certificate from a real web server.