📄 dhlib.c
字号:
#include <stdio.h>#include <openssl/bn.h>#include <fcntl.h>#include <string.h>#include "prime.h"static int primesInit = 0;static BIGNUM *g,*n;char *uRandStr(int len){ char tmpStr[5000]; int ur; int rc; int i; unsigned char c; if ( (len > 2048) || (len < 128)) return(NULL); ur = open("/dev/urandom",O_RDONLY); if (ur < 0) return(NULL); // get a random char and make sure the high bit is set while(1) { rc = read(ur,&c,1); if (rc != 1) { close(ur); return(NULL); } if (c & 0x80) break; } memset(tmpStr,0,5000); i=0; sprintf(&tmpStr[i],"%02x",c); for(i=2;i<len*2;i+=2) { rc = read(ur,&c,1); if (rc != 1) { close(ur); return(NULL); } sprintf(&tmpStr[i],"%02x",c); } close(ur); return(strdup(tmpStr)); }// int BN_mod_exp(BIGNUM *r, BIGNUM *a, const BIGNUM *p,// const BIGNUM *m, BN_CTX *ctx);static int initPrimes(){ static int inited=0; int rc; if (inited) return(0); inited=1; rc = BN_hex2bn(&g,gP); rc = BN_hex2bn(&n,nP);}int computeKey(BIGNUM **k,BIGNUM *X,BIGNUM *x){ BIGNUM *kTmp = *k; BN_CTX *ctx; int rc; initPrimes(); ctx = BN_CTX_new(); rc = BN_mod_exp(*k,X,x,n,ctx); BN_CTX_free(ctx); return(rc); }int getDHX(BIGNUM **resultX,BIGNUM **secretX){ BN_CTX *ctx; char *randNum; BIGNUM *x,*X; int rc; X = *resultX; x = *secretX; initPrimes(); // alice randNum = uRandStr(128); // get a if (randNum == NULL) { fprintf(stderr,"urandStr failed\n"); return(-2); } rc = BN_hex2bn(&x,randNum); X = BN_new(); ctx = BN_CTX_new(); rc = BN_mod_exp(X,g,x,n,ctx); BN_CTX_free(ctx);// pNum = BN_bn2hex(X);// secretNum = BN_bn2hex(x); // *secretX = x;// *resultX = X; return(0); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -