• 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 
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <gmssl/sm2.h>
15 #include <gmssl/ec.h>
16 #include <gmssl/error.h>
17 
18 
test_ec_named_curve(void)19 static int test_ec_named_curve(void)
20 {
21 	uint8_t buf[256];
22 	uint8_t *p = buf;
23 	const uint8_t *cp = buf;
24 	size_t len = 0;
25 	char *curves[] = {
26 		"sm2p256v1",
27 		"prime192v1",
28 		"prime256v1",
29 		"secp256k1",
30 		"secp384r1",
31 		"secp521r1",
32 	};
33 	int oid;
34 	int i;
35 
36 	for (i = 0; i < sizeof(curves)/sizeof(curves[0]); i++) {
37 		if ((oid = ec_named_curve_from_name(curves[i])) == OID_undef) {
38 			error_print();
39 			return -1;
40 		}
41 		if (ec_named_curve_to_der(oid, &p, &len) != 1) {
42 			error_print();
43 			return -1;
44 		}
45 	}
46 
47 	for (i = 0; i < sizeof(curves)/sizeof(curves[0]); i++) {
48 		if (ec_named_curve_from_der(&oid, &cp, &len) != 1) {
49 			error_print();
50 			return -1;
51 		}
52 		if (oid != ec_named_curve_from_name(curves[i])) {
53 			error_print();
54 			return -1;
55 		}
56 		format_print(stderr, 0, 4, "%s\n", ec_named_curve_name(oid));
57 	}
58 	(void)asn1_length_is_zero(len);
59 
60 	printf("%s() ok\n", __FUNCTION__);
61 	return 1;
62 }
63 
test_ec_point_print(void)64 static int test_ec_point_print(void)
65 {
66 	SM2_KEY sm2_key;
67 	uint8_t buf[256];
68 	uint8_t *p = buf;
69 	size_t len = 0;
70 
71 	if (sm2_key_generate(&sm2_key) != 1) {
72 		error_print();
73 		return -1;
74 	}
75 	if (sm2_point_to_der(&(sm2_key.public_key), &p, &len) != 1) {
76 		error_print();
77 		return -1;
78 	}
79 	ec_point_print(stderr, 0, 4, "ECPoint", buf, len);
80 
81 	printf("%s() ok\n", __FUNCTION__);
82 	return 1;
83 }
84 
test_ec_private_key_print(void)85 static int test_ec_private_key_print(void)
86 {
87 	SM2_KEY sm2_key;
88 	uint8_t buf[256];
89 	uint8_t *p = buf;
90 	const uint8_t *cp = buf;
91 	size_t len = 0;
92 	const uint8_t *d;
93 	size_t dlen;
94 
95 	if (sm2_key_generate(&sm2_key) != 1) {
96 		error_print();
97 		return -1;
98 	}
99 	if (sm2_private_key_to_der(&sm2_key, &p, &len) != 1
100 		|| asn1_sequence_from_der(&d, &dlen, &cp, &len) != 1
101 		|| asn1_length_is_zero(len) != 1) {
102 		error_print();
103 		return -1;
104 	}
105 	ec_private_key_print(stderr, 0, 4, "ECPrivateKey", d, dlen);
106 
107 	printf("%s() ok\n", __FUNCTION__);
108 	return 1;
109 }
110 
main(void)111 int main(void)
112 {
113 	if (test_ec_named_curve() != 1) goto err;
114 	if (test_ec_point_print() != 1) goto err;
115 	if (test_ec_private_key_print() != 1) goto err;
116 	printf("%s all tests passed\n", __FILE__);
117 	return 0;
118 err:
119 	error_print();
120 	return -1;
121 }
122