Tag:openssl demo animated
/* The following program utilizes the OpenSSL library to implement the DH algorithm, generate keys and calculate sessionkey*/#include <openssl/dh.h> #include <memory.h>int main () {DH * D1,*D2; BIO *b; int ret,size,i,len1,len2; Char sharekey1[128],sharekey2[128]; /* Construct DH data structure */d1=dh_new (); D2=dh_new (); /* Generate key parameters for D1 */RET=DH_GENERATE_PARAMETERS_EX (d1,64,dh_generator_2,null); if (ret!=1) {//prime_len,g is greater than 1, common 2 and 5 printf ("Dh_generate_parameters_ex err!\n"); return-1; }/* Check key parameters */Ret=dh_check (d1,&i);//i is set to 0 first, then through or equal to, get error message type if (ret!=1) {printf ("Dh_check err!\n"); if (i&dh_check_p_not_prime) printf ("P value is not prime\n"); if (i&dh_check_p_not_safe_prime) printf ("P value is not a SAFE prime\n"); if (i&dh_unable_to_check_generator) printf ("Unable to CHECK the GENERATOR value\n"); if (i&dh_not_suitable_generator) printf ("The G value is not a generator\n"); } printf ("DH parameters appear to be ok.\n"); /* Key size*/size=dh_size (D1); printf ("DH key1 Size:%d\n", size); /* Generate Public private key */Ret=dh_generate_key (D1); if (ret!=1) {printf ("Dh_generate_key err!\n"); return-1; }/* p and G are public key parameters, so you can copy */D2->p=bn_dup (D1->P); D2->g=bn_dup (D1->G); /* Generate a public private key for testing the generated shared key */Ret=dh_generate_key (D2); if (ret!=1) {printf ("Dh_generate_key err!\n"); return-1; }/* Check public key */Ret=dh_check_pub_key (d1,d1->pub_key,&i); if (ret!=1) {if (I&dh_check_pubkey_too_small) printf ("Pub key TOO SMALL \ n"); if (i&dh_check_pubkey_too_large) printf ("Pub key TOO LARGE \ n"); }/* Compute shared Key */Len1=dh_compute_key (SHAREKEY1,D2->PUB_KEY,D1); Len2=dh_compute_key (SHAREKEY2,D1->PUB_KEY,D2); if (len1!=len2) {printf ("Generate shared Key failed 1\n"); return-1; } if (memcmp (SHAREKEY1,SHAREKEY2,LEN1)!=0) {printf ("Generate shared Key failed 2\n"); return-1; } printf ("Generate shared key successfully \ n"); return 0;}
The DH algorithm in OpenSSL demo