/* calculate a pubKey out of a given priKey */ int SM2_standard_sign_keygeneration(unsigned char PriKey[], unsigned char Px[], unsigned char Py[]) { int i = 0; big d, PAx, PAy; epoint *PA; SM2_standard_init(); PA = epoint_init(); d = mirvar(0); PAx = mirvar(0); PAy = mirvar(0); bytes_to_big(SM2_NUMWORD, PriKey, d); ecurve_mult(d, G, PA); epoint_get(PA, PAx, PAy); big_to_bytes(SM2_NUMWORD, PAx, Px, TRUE); big_to_bytes(SM2_NUMWORD, PAy, Py, TRUE); i = Test_PubKey(PA); if (i) return i; else return 0; }
void BaseOT::PointToByteArray(BYTE* pBufIdx, int field_size, ECn &point) { int itmp; Big bigtmp; //compress to x-point and y-bit and convert to byte array itmp = point.get(bigtmp); //first store the y-bit pBufIdx[0] = (BYTE) (itmp & 0x01); //then store the x-coordinate (sec-param/8 + 4 byte size) big_to_bytes(field_size, bigtmp.getbig(), (char*) pBufIdx+1, true); }
// 计算 CDKEY 中 hash 散列的值 big key_hash(unsigned int Key, unsigned char Type, unsigned char Data, big rx, big ry) { unsigned char buf[128], m[132], sha_out[20]; unsigned long dw; int i, j, len, len2; sha sh; big hash; KEY tmp; tmp.a = Key; // 钥匙的值 m[0] = tmp.b[3]; // 取钥匙的第3个字节 m[1] = tmp.b[2]; // 取钥匙的第2个字节 m[2] = Type; // CDKEY 中类型的值 m[3] = Data; // CDKEY 中数据的值 // 循环将 RX 的值放入 m[] 数组中,作为用于生成散列的内容。 len = rx->len * 4; // 获得RX的长度 big_to_bytes(len, rx, (char*)buf, FALSE); // 将 rx 转成 数值 for (i = len - 1, j = 4; i >= 0; i--, j++) m[j] = buf[i]; // 循环将 rx 写入 m[] // 循环将 RY 的值放入 m[] 数组中,作为用于生成散列的内容。 len2 = ry->len * 4; // 获得RY的长度 big_to_bytes(len2, ry, (char*)buf, FALSE); // 将 ry 转成 数值 for (i = len2 - 1, j = len + 4; i >= 0; i--, j++) m[j] = buf[i]; // 循环将 ry 写入 m[] // 开始散列 shs_init(&sh); // 初始化 sha1 散列 for (i = 0; i < (4 + rx->len + ry->len); i++) shs_process(&sh, m[i]); // 将 m[] 写入 sha1 处理 shs_hash(&sh, (char*)sha_out); // 计算 sha1 散列值 memcpy(&dw, sha_out, 4); // 将前4字节写入 dw dw = dw & 0x7FFFFFFF; // 取后 31bit 数值 hash = mirvar(dw); return hash; // 返回31bit散列的值 }
// Input: MyPrivKey = Your private key // HisPubKey = Someones public key // Output: MyPrivKey has been destroyed for security reasons // HisPubKey = the secret key int DH1080_comp(char *MyPrivKey, char *HisPubKey) { int i=0, len, iRet; unsigned char SHA256digest[35], base64_tmp[160]; big b_myPrivkey, b_HisPubkey, b_theKey; // Verify base64 strings if((strspn(MyPrivKey, B64ABC) != strlen(MyPrivKey)) || (strspn(HisPubKey, B64ABC) != strlen(HisPubKey))) { memset(MyPrivKey, 0x20, strlen(MyPrivKey)); memset(HisPubKey, 0x20, strlen(HisPubKey)); return 0; } b_HisPubkey=mirvar(0); b_theKey=mirvar(0); len=b64toh(HisPubKey, base64_tmp); bytes_to_big(len, base64_tmp, b_HisPubkey); if(DH_verifyPubKey(b_HisPubkey)) { b_myPrivkey=mirvar(0); len=b64toh(MyPrivKey, base64_tmp); bytes_to_big(len, base64_tmp, b_myPrivkey); memset(MyPrivKey, 0x20, strlen(MyPrivKey)); powmod(b_HisPubkey, b_myPrivkey, b_prime1080, b_theKey); mirkill(b_myPrivkey); len=big_to_bytes(sizeof(base64_tmp), b_theKey, base64_tmp, FALSE); SHA256_memory(base64_tmp, len, SHA256digest); htob64(SHA256digest, HisPubKey, 32); iRet=1; } else iRet=0; ZeroMemory(base64_tmp, sizeof(base64_tmp)); ZeroMemory(SHA256digest, sizeof(SHA256digest)); mirkill(b_theKey); mirkill(b_HisPubkey); return iRet; }
void mcl_ecpbs_hash_epsilon(big result, epoint *alpha, epoint *beta, epoint *z, char *message, mcl_ecpbs_parameters *parameters) { int buffer_len, num_bytes = 0; int big_size; char *buffer, *pos; /* miracl *mip = get_mip(); */ /* FIXME do this dynamically: big_size_bits = mip->nib * 8; */ big_size = 20; /* 6 bigs for X and Y of alpha,beta,and z */ buffer_len = (6 * big_size) + strlen(message) + 1; epoint_norm(alpha); epoint_norm(beta); epoint_norm(z); /* compute: H(alpha->X|alpha->Y|beta->X|beta->Y|z->X|z->Y|msg) */ buffer = calloc(1, buffer_len); pos = buffer; num_bytes = big_to_bytes(big_size, alpha->X, pos, FALSE); pos = pos + num_bytes; num_bytes = big_to_bytes(big_size, alpha->Y, pos, FALSE); pos = pos + num_bytes; num_bytes = big_to_bytes(big_size, beta->X, pos, FALSE); pos = pos + num_bytes; num_bytes = big_to_bytes(big_size, beta->Y, pos, FALSE); pos = pos + num_bytes; num_bytes = big_to_bytes(big_size, z->X, pos, FALSE); pos = pos + num_bytes; num_bytes = big_to_bytes(big_size, z->Y, pos, FALSE); pos = pos + num_bytes; memcpy(pos, message, strlen(message)); mcl_ecpbs_Hhash(result, buffer, parameters->q); free(buffer); }
/* SM2 signature algorithm */ int SM2_standard_sign(unsigned char *message, int len, unsigned char ZA[], unsigned char rand[], unsigned char d[], unsigned char R[], unsigned char S[]) { unsigned char hash[SM3_len / 8]; int M_len = len + SM3_len / 8; unsigned char *M = NULL; int i; big dA, r, s, e, k, KGx, KGy; big rem, rk, z1, z2; epoint *KG; i = SM2_standard_init(); if (i) return i; //initiate dA = mirvar(0); e = mirvar(0); k = mirvar(0); KGx = mirvar(0); KGy = mirvar(0); r = mirvar(0); s = mirvar(0); rem = mirvar(0); rk = mirvar(0); z1 = mirvar(0); z2 = mirvar(0); bytes_to_big(SM2_NUMWORD, d, dA); //cinstr(dA, d); KG = epoint_init(); //step1, set M = ZA || M M = (char *)malloc(sizeof(char)*(M_len + 1)); memcpy(M, ZA, SM3_len / 8); memcpy(M + SM3_len / 8, message, len); //step2, generate e = H(M) SM3_256(M, M_len, hash); bytes_to_big(SM3_len / 8, hash, e); //step3:generate k bytes_to_big(SM3_len / 8, rand, k); //step4:calculate kG ecurve_mult(k, G, KG); //step5:calculate r epoint_get(KG, KGx, KGy); add(e, KGx, r); divide(r, para_n, rem); //judge r = 0 or n + k = n? add(r, k, rk); if (Test_Zero(r) | Test_n(rk)) return ERR_GENERATE_R; //step6:generate s incr(dA, 1, z1); xgcd(z1, para_n, z1, z1, z1); multiply(r, dA, z2); divide(z2, para_n, rem); subtract(k, z2, z2); add(z2, para_n, z2); multiply(z1, z2, s); divide(s, para_n, rem); //judge s = 0? if (Test_Zero(s)) return ERR_GENERATE_S ; big_to_bytes(SM2_NUMWORD, r, R, TRUE); big_to_bytes(SM2_NUMWORD, s, S, TRUE); free(M); return 0; }
int crypto_dh(unsigned char *s,const unsigned char* pk,const unsigned char *sk) { int i,promptr; ecn2 P; big A,B,p,a[2]; zzn2 x,y,psi[2]; miracl instance; /* create miracl workspace on the stack */ /* Specify base 16 here so that HEX can be read in directly without a base-change */ miracl *mip=mirsys(&instance,WORDS*16,16); /* size of bigs is fixed */ char mem_big[MR_BIG_RESERVE(17)]; /* we need 17 bigs... */ memset(mem_big, 0, MR_BIG_RESERVE(17)); /* clear the memory */ A=mirvar_mem(mip, mem_big, 0); /* Initialise big numbers */ B=mirvar_mem(mip, mem_big, 1); x.a=mirvar_mem(mip, mem_big, 2); x.b=mirvar_mem(mip, mem_big, 3); #ifndef COMPRESSED y.a=mirvar_mem(mip, mem_big, 4); y.b=mirvar_mem(mip, mem_big, 5); #endif a[0]=mirvar_mem(mip, mem_big, 6); a[1]=mirvar_mem(mip, mem_big, 7); p=mirvar_mem(mip, mem_big, 8); P.x.a=mirvar_mem(mip, mem_big, 9); P.x.b=mirvar_mem(mip, mem_big, 10); P.y.a=mirvar_mem(mip, mem_big, 11); P.y.b=mirvar_mem(mip, mem_big, 12); P.z.a=mirvar_mem(mip, mem_big, 13); P.z.b=mirvar_mem(mip, mem_big, 14); P.marker=MR_EPOINT_INFINITY; psi[0].a=mirvar_mem(mip, mem_big, 15); psi[0].b=mirvar_mem(mip, mem_big, 16); promptr=0; init_big_from_rom(p,WORDS,rom,16,&promptr); /* Read in prime modulus p from ROM */ init_big_from_rom(B,WORDS,rom,16,&promptr); /* Read in curve parameter B from ROM */ init_big_from_rom(psi[0].a,WORDS,rom,16,&promptr); init_big_from_rom(psi[0].b,WORDS,rom,16,&promptr); init_big_from_rom(x.a,WORDS,rom,16,&promptr); init_big_from_rom(x.b,WORDS,rom,16,&promptr); #ifndef COMPRESSED init_big_from_rom(y.a,WORDS,rom,16,&promptr); init_big_from_rom(y.b,WORDS,rom,16,&promptr); #endif convert(mip,1,A); /* Fix A=1 */ /* offline calculations */ ecurve_init(mip,A,B,p,MR_PROJECTIVE); mip->TWIST=TRUE; /* Alice calculates secret key */ bytes_to_big(mip,16,pk,x.a); bytes_to_big(mip,16,&pk[16],x.b); bytes_to_big(mip,16,sk,a[0]); bytes_to_big(mip,16,&sk[16],a[1]); #ifndef COMPRESSED bytes_to_big(mip,16,&pk[32],y.a); bytes_to_big(mip,16,&pk[48],y.b); if (!ecn2_set(mip,&x,&y,&P)) { memset(mem_big, 0, MR_BIG_RESERVE(17)); mirexit(mip); return -1; } #else if (!ecn2_setx(mip,&x,&P)) { memset(mem_big, 0, MR_BIG_RESERVE(17)); mirexit(mip); return -1; } #endif ecn2_mul2_gls(mip,a,&P,psi,&P); ecn2_getx(&P,&x); #ifdef COMPRESSED zzn2_sqr(mip,&x,&x); /* I tossed y, so I might have wrong sign.. */ #endif big_to_bytes(mip,16,x.a,s,TRUE); big_to_bytes(mip,16,x.b,&s[16],TRUE); memset(mem_big, 0, MR_BIG_RESERVE(17)); mirexit(mip); return 0; }
int crypto_dh_keypair(unsigned char* pk,unsigned char *sk) { int i,promptr; big A,B,p,a[2]; zzn2 x,y,psi[2]; miracl instance; /* create miracl workspace on the stack */ ebrick binst; /* Specify base 16 here so that HEX can be read in directly without a base-change */ miracl *mip=mirsys(&instance,WORDS*16,16); /* size of bigs is fixed */ char mem_big[MR_BIG_RESERVE(11)]; /* we need 10 bigs... */ memset(mem_big, 0, MR_BIG_RESERVE(11)); /* clear the memory */ A=mirvar_mem(mip, mem_big, 0); /* Initialise big numbers */ B=mirvar_mem(mip, mem_big, 1); x.a=mirvar_mem(mip, mem_big, 2); x.b=mirvar_mem(mip, mem_big, 3); y.a=mirvar_mem(mip, mem_big, 4); y.b=mirvar_mem(mip, mem_big, 5); a[0]=mirvar_mem(mip, mem_big, 6); a[1]=mirvar_mem(mip, mem_big, 7); p=mirvar_mem(mip, mem_big, 8); psi[0].a=mirvar_mem(mip, mem_big, 9); psi[0].b=mirvar_mem(mip, mem_big, 10); promptr=0; init_big_from_rom(p,WORDS,rom,16,&promptr); /* Read in prime modulus p from ROM */ init_big_from_rom(B,WORDS,rom,16,&promptr); /* Read in curve parameter B from ROM */ init_big_from_rom(psi[0].a,WORDS,rom,16,&promptr); init_big_from_rom(psi[0].b,WORDS,rom,16,&promptr); convert(mip,1,A); /* Fix A=1 */ ecn2_brick_init(&binst,prom,A,B,p,6,128); /* Alices key gen calculation */ #ifdef HAVE_MAIN for (i=0;i<32;i++) sk[i]=rand(); #else randombytes(sk,32); #endif sk[15]&=0x3f; sk[31]&=0x3f; bytes_to_big(mip,16,sk,a[0]); bytes_to_big(mip,16,&sk[16],a[1]); ecn2_mul_brick_gls(mip,&binst,a,psi,&x,&y); big_to_bytes(mip,16,x.a,pk,TRUE); big_to_bytes(mip,16,x.b,&pk[16],TRUE); #ifndef COMPRESSED big_to_bytes(mip,16,y.a,&pk[32],TRUE); big_to_bytes(mip,16,y.b,&pk[48],TRUE); #endif memset(mem_big, 0, MR_BIG_RESERVE(11)); mirexit(mip); return 0; }
int SM9_standard_key_encap(unsigned char hid[], unsigned char *IDB, unsigned char rand[], unsigned char Ppub[], unsigned char C[], unsigned char K[], int Klen) { big h, x, y, r; epoint *Ppube, *QB, *Cipher; unsigned char *Z = NULL; int Zlen, buf, i, num = 0; zzn12 g, w; //initiate h = mirvar(0); r = mirvar(0); x = mirvar(0); y = mirvar(0); QB = epoint_init(); Ppube = epoint_init(); Cipher = epoint_init(); zzn12_init(&g); zzn12_init(&w); bytes_to_big(BNLEN, Ppub, x); bytes_to_big(BNLEN, Ppub + BNLEN, y); epoint_set(x, y, 0, Ppube); //----------Step1:calculate QB=[H1(IDB||hid,N)]P1+Ppube---------- Zlen = strlen(IDB) + 1; Z = (char *)malloc(sizeof(char)*(Zlen + 1)); if(Z == NULL) return SM9_ASK_MEMORY_ERR; memcpy(Z, IDB, strlen(IDB)); memcpy(Z + strlen(IDB), hid, 1); buf = SM9_standard_h1(Z, Zlen, N, h); free(Z); if(buf) return buf; printf("\n************************ H1(IDB||hid,N) ************************\n"); cotnum(h, stdout); ecurve_mult(h, P1, QB); ecurve_add(Ppube, QB); printf("\n*******************QB:=[H1(IDB||hid,N)]P1+Ppube*****************\n"); epoint_get(QB, x, y); cotnum(x, stdout); cotnum(y, stdout); //-------------------- Step2:randnom ------------------- bytes_to_big(BNLEN, rand, r); printf("\n***********************randnum r: ******************************\n"); cotnum(r, stdout); //----------------Step3:C=[r]QB------------------------ ecurve_mult(r, QB, Cipher); epoint_get(Cipher, x, y); printf("\n*********************** C=[r]QB: ******************************\n"); cotnum(x, stdout); cotnum(y, stdout); big_to_bytes(BNLEN, x, C, 1); big_to_bytes(BNLEN, y, C + BNLEN, 1); //----------------Step4:g=e(Ppube,P2)------------------------ if(!ecap(P2, Ppube, para_t, X, &g)) return SM9_MY_ECAP_12A_ERR; //test if a ZZn12 element is of order q if(!member(g, para_t, X)) return SM9_MEMBER_ERR; printf("\n***********************g=e(Ppube,P2):****************************\n"); zzn12_ElementPrint(g); //----------------Step5:w=g^r------------------------ w = zzn12_pow(g, r); printf("\n************************* w=g^r:*********************************\n"); zzn12_ElementPrint(w); //----------------Step6:K=KDF(C||w||IDB,klen)------------------------ Zlen = strlen(IDB) + BNLEN * 14; Z = (char *)malloc(sizeof(char)*(Zlen + 1)); if(Z == NULL) return SM9_ASK_MEMORY_ERR; LinkCharZzn12(C, BNLEN * 2, w, Z, BNLEN * 14); memcpy(Z + BNLEN * 14, IDB, strlen(IDB)); SM3_kdf(Z, Zlen, Klen, K); free(Z); //----------------test if K equals 0------------------------ printf("\n******************* K=KDF(C||w||IDB,klen):***********************\n"); for(i = 0; i < Klen; i++) { if(K[i] == 0) num += 1; printf("%02x", K[i]); } if(num == Klen) return SM9_ERR_K1_ZERO; return 0; }
// Input: priv_key = buffer of 200 bytes // pub_key = buffer of 200 bytes // Output: priv_key = Your private key // pub_key = Your public key int DH1080_gen(char *priv_key, char *pub_key) { unsigned char raw_buf[160], iniHash[33]; unsigned long seed; int len, iRet; big b_privkey, b_pubkey; csprng myRNG; FILE *hRnd; priv_key[0]='0'; priv_key[1]='\0'; pub_key[0]='0'; pub_key[1]='\0'; hRnd = fopen("/dev/urandom", "r"); // don't use /dev/random, it's a blocking device if(!hRnd) return 0; b_privkey=mirvar(0); b_pubkey=mirvar(0); // #*#*#*#*#* RNG START #*#*#*#*#* time((time_t *)&seed); seed ^= (long)hRnd << 16; if(fread(raw_buf, 1, sizeof(raw_buf), hRnd) < 32) { ZeroMemory(raw_buf, sizeof(raw_buf)); fclose(hRnd); mirkill(b_privkey); mirkill(b_pubkey); return 0; } fclose(hRnd); sha_file(iniPath, iniHash); memXOR(raw_buf+128, iniHash, 32); sha_file((unsigned char *)get_irssi_config(), iniHash); memXOR(raw_buf+128, iniHash, 32); ZeroMemory(iniHash, sizeof(iniHash)); // first 128 byte in raw_buf: output from /dev/urandom // last 32 byte in raw_buf: SHA-256 digest from blow.ini and irssi.conf seed *= (unsigned long)mip; strong_init(&myRNG, sizeof(raw_buf), raw_buf, (unsigned int)seed); strong_rng(&myRNG); strong_bigdig(&myRNG, 1080, 2, b_privkey); strong_kill(&myRNG); seed=0; // #*#*#*#*#* RNG END #*#*#*#*#* powltr(2, b_privkey, b_prime1080, b_pubkey); if(DH_verifyPubKey(b_pubkey)) { len=big_to_bytes(sizeof(raw_buf), b_privkey, raw_buf, FALSE); htob64(raw_buf, priv_key, len); len=big_to_bytes(sizeof(raw_buf), b_pubkey, raw_buf, FALSE); htob64(raw_buf, pub_key, len); iRet=1; } else iRet=0; ZeroMemory(raw_buf, sizeof(raw_buf)); mirkill(b_privkey); mirkill(b_pubkey); return iRet; }
/* * function encodeByteArrayToPoint : Encodes the given byte array into a point. * If the given byte array can not be encoded to a point, returns 0. * param dlog : Pointer to the native Dlog object. * param binaryString : The byte array to encode. * param k : k is the maximum length of a string to be converted to a Group Element of this group. * If a string exceeds the k length it cannot be converted. * return : The created point or 0 if the point cannot be created. */ JNIEXPORT jlong JNICALL Java_edu_biu_scapi_primitives_dlog_miracl_MiraclDlogECFp_encodeByteArrayToPoint (JNIEnv * env, jobject, jlong m, jbyteArray binaryString, jint k){ //Pseudo-code: /*If the length of binaryString exceeds k then throw IndexOutOfBoundsException. Let L be the length in bytes of p Choose a random byte array r of length L – k – 2 bytes Prepare a string newString of the following form: r || binaryString || binaryString.length (where || denotes concatenation) (i.e., the least significant byte of newString is the length of binaryString in bytes) Convert the result to a BigInteger (bIString) Compute the elliptic curve equation for this x and see if there exists a y such that (x,y) satisfies the equation. If yes, return (x,y) Else, go back to step 3 (choose a random r etc.) up to 80 times (This is an arbitrary hard-coded number). If did not find y such that (x,y) satisfies the equation after 80 trials then return null. */ /* convert the accepted parameters to MIRACL parameters*/ miracl* mip = (miracl*)m; jbyte* string = (jbyte*) env->GetByteArrayElements(binaryString, 0); int len = env->GetArrayLength(binaryString); if (len > k){ env ->ReleaseByteArrayElements(binaryString, string, 0); return 0; } big x, p; x = mirvar(mip, 0); p = mip->modulus; int l = logb2(mip, p)/8; char* randomArray = new char[l-k-2]; char* newString = new char[l - k - 1 + len]; memcpy(newString+l-k-2, string, len); newString[l - k - 2 + len] = (char) len; int counter = 0; bool success = 0; csprng rng; srand(time(0)); long seed; char raw = rand(); time((time_t*)&seed); strong_init(&rng,1,&raw,seed); do{ for (int i=0; i<l-k-2; i++){ randomArray[i] = strong_rng(&rng); } memcpy(newString, randomArray, l-k-2); bytes_to_big(mip, l - k - 1 + len, newString, x); //If the number is negative, make it positive. if(exsign(x)== -1){ absol(x, x); } //epoint_x returns true if the given x value leads to a valid point on the curve. //if failed, go back to choose a random r etc. success = epoint_x(mip, x); counter++; } while((!success) && (counter <= 80)); //we limit the amount of times we try to 80 which is an arbitrary number. epoint* point = 0; if (success){ point = epoint_init(mip); epoint_set(mip, x, x, 0, point); } char* temp = new char[l - k - 1 + len]; big_to_bytes(mip,l - k - 1 + len , x, temp, 1); //Delete the allocated memory. env ->ReleaseByteArrayElements(binaryString, string, 0); mirkill(x); delete(randomArray); delete(newString); //Return the created point. return (long) point; }