• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2014-2022 The GmSSL Project. All Rights Reserved.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the License); you may
5  *  not use this file except in compliance with the License.
6  *
7  *  http://www.apache.org/licenses/LICENSE-2.0
8  */
9 
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <gmssl/sm2.h>
14 #include <gmssl/error.h>
15 
16 
main(void)17 int main(void)
18 {
19 	SM2_KEY sm2_key;
20 	SM2_KEY pub_key;
21 	SM2_SIGN_CTX sign_ctx;
22 	unsigned char dgst[32];
23 	unsigned char sig[SM2_MAX_SIGNATURE_SIZE];
24 	size_t siglen;
25 	int ret;
26 
27 	sm2_key_generate(&sm2_key);
28 
29 	memcpy(&pub_key, &sm2_key, sizeof(SM2_POINT));
30 
31 	// sign without signer ID (and Z value)
32 	sm2_sign_init(&sign_ctx, &sm2_key, NULL, 0);
33 	sm2_sign_update(&sign_ctx, (unsigned char *)"hello ", strlen("hello "));
34 	sm2_sign_update(&sign_ctx, (unsigned char *)"world", strlen("world"));
35 	sm2_sign_finish(&sign_ctx, sig, &siglen);
36 	format_bytes(stdout, 0, 0, "signature", sig, siglen);
37 
38 	// digest and verify
39 	sm3_digest((unsigned char *)"hello world", strlen("hello world"), dgst);
40 	ret = sm2_verify(&pub_key, dgst, sig, siglen);
41 	printf("verify result: %s\n", ret == 1 ? "success" : "failure");
42 
43 	// use verify update API
44 	sm2_verify_init(&sign_ctx, &pub_key, NULL, 0);
45 	sm2_verify_update(&sign_ctx, (unsigned char *)"hello world", strlen("hello world"));
46 	ret = sm2_verify_finish(&sign_ctx, sig, siglen);
47 	printf("verify result: %s\n", ret == 1 ? "success" : "failure");
48 
49 	// sign use default signer ID
50 	sm2_sign_init(&sign_ctx, &sm2_key, SM2_DEFAULT_ID, SM2_DEFAULT_ID_LENGTH);
51 	sm2_sign_update(&sign_ctx, (unsigned char *)"hello ", strlen("hello "));
52 	sm2_sign_update(&sign_ctx, (unsigned char *)"world", strlen("world"));
53 	sm2_sign_finish(&sign_ctx, sig, &siglen);
54 	format_bytes(stdout, 0, 0, "signature", sig, siglen);
55 
56 	sm2_verify_init(&sign_ctx, &pub_key, SM2_DEFAULT_ID, SM2_DEFAULT_ID_LENGTH);
57 	sm2_verify_update(&sign_ctx, (unsigned char *)"hello world", strlen("hello world"));
58 	ret = sm2_verify_finish(&sign_ctx, sig, siglen);
59 	printf("verify result: %s\n", ret == 1 ? "success" : "failure");
60 
61 	return 0;
62 }
63