【sm2算法】基于mbedtls开源库国密算法的使用(二)
在上一节中我们讲解了mbedtls基础知识:sm2环境、sm2公私钥的存储以及sm2公私钥的生成。
在这一节我们就反着来玩一下,开发场景如下:
我们已经明确的知道sm2加密算法的公私钥,如何将其放入sm2环境中???
涉及到的具体方法
/** * 初始化 sm2 环境 * * @param ctx 传入sm2环境指针 * @return 0——成功 否则失败 */ int sm2_init(sm2_context *ctx) /** * 将 传入的私钥字符串 赋值给sm2环境中 * @param ctx sm2环境 * @param buf 私钥字符串 * @return 0——成功 否则失败 */ int sm2_read_string_private(sm2_context *ctx, const char *buf) /** * 将 传入的公钥字符串 赋值给sm2环境中 * @param ctx sm2环境 * @param x 公钥字符串 X 分支值 * @param y 公钥字符串 Y 分支值 * @return 0——成功 否则失败 */ int sm2_read_string_public(sm2_context *ctx, const char *x, const char *y)
代码实现
#include <stdio.h>
#include "SSL/sm2/sm2.h"
int main()
{
//第一步:编写公私钥匙
unsigned char priKey[] = "9f1d21c1ed8c0ba167cd9860163c031938f536033880413fbac520124efd9ec6";
unsigned char pukKeyX[] = "594D7C9528BEF7E3EDA6CB2466D1A21BEE6141FB8486ABD04DCD4B4A48675DA7";
unsigned char pukKeyY[] = "68F7249024545F886C51B39BF1A215535B1EDF9ABAFE4AA97E3EE39532FE596B";
//第二步:初始化sm2环境
sm2_context ctx;
int result = -1;
result = sm2_init(&ctx);
if (result != 0)
{
printf("sm2_init fail
");
return -1;
}
//第三步:将私钥写入环境中并打印
result = sm2_read_string_private(&ctx, priKey);
if (result != 0)
{
printf("sm2_read_string_private fail
");
return -1;
}
//第四步:将公钥写入环境中并打印
result = sm2_read_string_public(&ctx, pukKeyX, pukKeyY);
if (result != 0)
{
printf("sm2_read_string_public fail
");
return -1;
}
int i;
for (i = 0; i < ctx.d.n; i++)
{
printf("%016lx ", *(ctx.d.p + i));
}
printf("
");
for (i = 0; i < ctx.Pb.X.n; i++)
{
printf("%016lx ", *(ctx.Pb.X.p + i));
}
printf("
");
for (i = 0; i < ctx.Pb.Y.n; i++)
{
printf("%016lx ", *(ctx.Pb.Y.p + i));
}
printf("
");
return 0;
}
效果展示
注意细节
细心的同学会发现,打印的公私钥顺序和我们写的有些颠倒 ,这个现象我们在上一节已经说明了,是因为我们电脑是以小端模式来存储我们的数据的,所以各组数据会有所颠倒,这个特性记住就可以了。
