SM2算法生成的私钥以及公钥位数过大(341位和65位)

fernand93 2017-10-11 11:13:44
以下是生成公钥和私钥的代码,不知为何,生成的公钥和私钥与标准的位数相差甚远,但是参数设定与标准设定相同,请大佬赐教,有急用,谢谢啦
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/bio.h>
#include <openssl/x509.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/ecdsa.h>
#include <openssl/ecdh.h>

#include "sm3.h"
#include "sm2.h"
#define PRIVKEY "static unsigned char privkey[%d] = {"
#define PUBKEY "static const unsigned char pubkey[%d] = {"
#define ENDKEY "\n};\n"
#pragma comment(lib,"libeay32.lib")

#define ABORT do { \
fflush(stdout); \
fprintf(stderr, "%s:%d: ABORT\n", __FILE__, __LINE__); \
ERR_print_errors_fp(stderr); \
exit(1); \
} while (0)

static const char rnd_seed[] = "string to make the random number generator think it has entropy";

void BNPrintf(BIGNUM* bn)
{
char *p=NULL;
p=BN_bn2hex(bn);
printf("%s",p);
OPENSSL_free(p);
}


int main()
{
//生成摘要

int ilen = 3;
unsigned char output[32];
unsigned char digest[1388][32];
sm3_context ctx3;
BN_CTX *ctx = NULL;
BIGNUM *p, *a, *b;
EC_GROUP *group;
EC_POINT *P, *Q, *R;
BIGNUM *x, *y, *z;
EC_KEY *eckey = NULL;

unsigned char *signature = NULL;
int sig_len;
//FILE *fp;
char pubkey[341][5]={0};
char prikey[65][5]={0};
int i=0,cs=0,er=0;
int aa=0,bb=0,cc=0;
char sta[16][5]={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
char all2sign[1388][72][2][5];/*72是由签名长度决定*/
int sta10[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int all10sign[1388][72];
unsigned char qq[1000];
int longsig[1387];
//int ilen = 3;
//unsigned char output[32];

//sm3_context ctx;
FILE*tp; FILE*mp; FILE*np;
FILE *file;
char buf[1200];

int len2=0,j=0,k=0;
unsigned char array [1389][600];

unsigned char bufpri[341], bufpub[65];
unsigned char *pp;
int len;
int sl;

for(cs=0; cs < 1; cs++)
{CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
ERR_load_crypto_strings();
RAND_seed(rnd_seed, sizeof rnd_seed);

/*SM2_Test_Vecotor();*/

//int len2=0,i=0,j=0,k=0;
//unsigned char array [1389][500];

CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
ERR_load_crypto_strings();
RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */

ctx = BN_CTX_new();
if (!ctx) ABORT;

/* Curve SM2 (Chinese National Algorithm) */
//http://www.oscca.gov.cn/News/201012/News_1197.htm
p = BN_new();
a = BN_new();
b = BN_new();
if (!p || !a || !b) ABORT;
group = EC_GROUP_new(EC_GFp_mont_method()); /* applications should use EC_GROUP_new_curve_GFp
* so that the library gets to choose the EC_METHOD */
if (!group) ABORT;

if (!BN_hex2bn(&p, "8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3")) ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL)) ABORT;
if (!BN_hex2bn(&a, "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498")) ABORT;
if (!BN_hex2bn(&b, "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A")) ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx)) ABORT;

P = EC_POINT_new(group);
Q = EC_POINT_new(group);
R = EC_POINT_new(group);
if (!P || !Q || !R) ABORT;

x = BN_new();
y = BN_new();
z = BN_new();
if (!x || !y || !z) ABORT;

// sm2 testing P256 Vetor
// p:8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3
// a:787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498
// b:63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A
// xG 421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D
// yG 0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2
// n: 8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7

if (!BN_hex2bn(&x, "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D")) ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 0, ctx)) ABORT;
if (!EC_POINT_is_on_curve(group, P, ctx)) ABORT;
if (!BN_hex2bn(&z, "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7")) ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one())) ABORT;

if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx)) ABORT;
fprintf(stdout, "\nChinese sm2 algorithm test -- Generator:\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn(&z, "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2")) ABORT;
if (0 != BN_cmp(y, z)) ABORT;

fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 256) ABORT;
fprintf(stdout, " ok\n");

fprintf(stdout, "verify group order ...");
fflush(stdout);
if (!EC_GROUP_get_order(group, z, ctx)) ABORT;
if (!EC_GROUP_precompute_mult(group, ctx)) ABORT;
if (!EC_POINT_mul(group, Q, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_is_at_infinity(group, Q)) ABORT;
fflush(stdout);
fprintf(stdout, " ok\n");

//testing ECDSA for SM2
/* create new ecdsa key */
if ((eckey = EC_KEY_new()) == NULL)
goto builtin_err;
if (EC_KEY_set_group(eckey, group) == 0)
{
fprintf(stdout," failed\n");
goto builtin_err;
}
/* create key */
if (!EC_KEY_generate_key(eckey))
{
fprintf(stdout," failed\n");
goto builtin_err;
}

pp = bufpri;
len =i2d_ECPrivateKey(eckey,&pp);
if (!len)
{
printf("Error:i2d_SM2PrivateKey()\n");
EC_KEY_free(eckey);
return -1;
}

printf(PRIVKEY,len);
for (i=0; i<len; i++)
{
if ( !(i % 10) )
printf("\n");
if(i==len-1)
printf("0x%02X ",bufpri[i]);
else
printf("0x%02X , ",bufpri[i]);
}
printf(ENDKEY);


/* check key */
if (!EC_KEY_check_key(eckey))
{
fprintf(stdout," failed\n");
goto builtin_err;
}
pp = bufpub;
len = i2o_ECPublicKey(eckey,&pp);
if (!len)
{
printf("Error:i2o_SM2PublicKey()\n");
EC_KEY_free(eckey);
return -1;
}

printf(PUBKEY,len);
for (i=0; i<len; i++)
{
if ( !(i % 10) )
printf("\n");
if(i==len-1)
printf("0x%02X ",bufpub[i]);
else
printf("0x%02X , ",bufpub[i]);
}
printf(ENDKEY);

//EC_KEY_free(eckey);

EC_KEY_free(eckey);
eckey = NULL;
builtin_err:

EC_POINT_free(P);
EC_POINT_free(Q);
EC_POINT_free(R);
EC_GROUP_free(group);
BN_CTX_free(ctx);


CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
ERR_remove_state(0);
CRYPTO_mem_leaks_fp(stderr);

};
...全文
1567 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2018-03-23
  • 打赏
  • 举报
回复
有时不将“调用函数名字+各参数值,进入函数后各参数值,中间变量值,退出函数前准备返回的值,返回函数到调用处后函数名字+各参数值+返回值”这些信息写日志到文件中是无论如何也发现不了问题在哪里的,包括捕获各种异常、写日志到屏幕、单步或设断点或生成core或dmp文件、……这些方法都不行! 写日志到文件参考下面:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
    #pragma warning(disable:4996)
    #include <windows.h>
    #include <io.h>
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  _vsnprintf         vsnprintf
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef _MSC_VER
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    _vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;

    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
int main(int argc,char * argv[]) {
    int i;
#ifdef _MSC_VER
    InitializeCriticalSection(&cs_log);
#else
    pthread_mutex_init(&cs_log,NULL);
#endif
    for (i=0;i<10000;i++) {
        Log("This is a Log %04d from FILE:%s LINE:%d\n",i, __FILE__, __LINE__);
    }
#ifdef _MSC_VER
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}
//1-79行添加到你带main的.c或.cpp的那个文件的最前面
//81-86行添加到你的main函数开头
//90-94行添加到你的main函数结束前
//在要写LOG的地方仿照第88行的写法写LOG到文件MyLog1.log中
walibao_Miss 2018-03-22
  • 打赏
  • 举报
回复
不知道楼主最后有没有搞清楚。刚刚开始研究国密算法,请赐教。

69,364

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧