一、生成密钥与读取的过程
/* 生成公钥 */
BIO_free_all( bp );
---------------------------------------------------------------------------------------------------------------------------------
/*从文件读取私钥*/
OpenSSL_add_all_algorithms();
BIO* bp = BIO_new( BIO_s_file() );
BIO_read_filename( bp, "private.pem" );
char passwd[]="1234";
RSA* rsaK = PEM_read_bio_RSAPrivateKey( bp, NULL, NULL, passwd );
-----------------------------------------------------------------------------------------------------------------------------------
/*从文件读取公钥*/
OpenSSL_add_all_algorithms();
BIO* bp = BIO_new( BIO_s_file() );
BIO_read_filename( bp, "public.pem" );
RSA* rsaK = PEM_read_bio_RSAPublicKey( bp, NULL, NULL, NULL );
二、使用ecdsa签名
/* 签名函数 */
static unsigned int sign_ecdsa(unsigned char *sig,const unsigned char *buf,int len)
{
unsigned int sign_len = MAXSIGLEN;
EC_KEY *ec_key = NULL;
BIO* bp = BIO_new( BIO_s_file() );
BIO_read_filename( bp, "ec_key.pem" );
ec_key = PEM_read_bio_ECPrivateKey(bp, NULL, NULL, NULL);
if(ec_key == NULL)
{
printf( "Error:d2i_ECPrivateKey()\n");
return -1;
}
/* 数据签名 */
if(!ECDSA_sign(0,buf, len, sig,&sign_len,ec_key))
{
printf("Error:ECDSA_sign()");
EC_KEY_free(ec_key);
return -1;
}
EC_KEY_free(ec_key);
return sign_len;
}
/*签名过程*/
int openssl_ecdsa_sign(void)
{
const char message[] = {"E576996C449B4597"};
unsigned char *signature,digest[32]={0};
char sign_str[512] = {0};
unsigned int dgst_len = 0;
EVP_MD_CTX md_ctx;
EVP_MD_CTX_init(&md_ctx);
/*散列算法*/
EVP_DigestInit(&md_ctx, EVP_sha256());
EVP_DigestUpdate(&md_ctx, (const void*)message, strlen(message));
EVP_DigestFinal(&md_ctx, digest, &dgst_len);
signature=(unsigned char *)malloc(512);
int len = sign(signature,(unsigned char*)&digest,dgst_len);
int i=0;
for(i=0; i<len; i++)
{
sprintf(sign_str + 2*i, "%02X", signature[i]);
}
free(signature);
td_printf(0, "sign = %s", sign_str);
FILE *fp = fopen("sign_file.txt","w");
fwrite(sign_str, 1, strlen(sign_str), fp);
fclose(fp);
return 0;
}