提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在Linux中运行调用gmp/openssl库函数的C?如下代码
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <openssl/bn.h>
int initrandom(mpz_t key, unsigned long n){
BIGNUM *Rand_a;
unsigned char mpz_bin[n];
Rand_a = BN_new();
BN_rand(Rand_a, n, 0, 0);
BN_bn2bin(Rand_a, mpz_bin);
mpz_import(key,n/8,1,sizeof(mpz_bin[0]),0,0,mpz_bin);
return 1;
}
int main(){
mpz_t key;
mpz_init(key);
int ans=initrandom(key,10);
printf("hello,world=%lld",key);
return;
}在这里插入代码片
一、安装gmp、openssl
1、openssl
查看是否安装:openssl version -a
安装openssl:sudo yum install openssl
$ openssl version -a
OpenSSL 1.0.2k-fips 26 Jan 2017
built on: reproducible build, date unspecified
platform: linux-x86_64
options: bn(64,64) md2(int) rc4(16x,int) des(idx,cisc,16,int) idea(int) blowfish(idx)
compiler: gcc -I. -I.. -I../include -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DKRB5_MIT -m64 -DL_ENDIAN -Wall -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -Wa,--noexecstack -DPURIFY -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DRC4_ASM -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM
OPENSSLDIR: "/etc/pki/tls"
engines: rdrand dynamic
2、 gmp
安装gmp: sudo yum install gmp
[root@centos7 centos7]# sudo yum install gmp-devel.x86_64
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirrors.ustc.edu.cn
* extras: mirrors.cn99.com
* updates: mirrors.cn99.com
base | 3.6 kB 00:00:00
extras | 2.9 kB 00:00:00
updates | 2.9 kB 00:00:00
Package 1:gmp-devel-6.0.0-15.el7.x86_64 already installed and latest version
Nothing to do
二、调用gmp、openssl库
gmp直接添加
#include <gmp.h>
openssl根据调用的函数添加对应的库
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
三、编译
重点是添加 -lcrypto 这个动态链接库
gcc -o main random.c -lgmp -lssl -lcrypto
总结
使用的比较仓仓促,没有深入了解,如果要熟练使用参考下方链接。
参考链接
gmp库粗略介绍
Openssl之大数运算BN
https://blog.csdn.net/test1280/article/details/105255305/
http://blog.sina.com.cn/s/blog_45497dfa0100nxi3.html