xref: /openssl/test/recipes/15-test_gensm2.t (revision b6461792)
1#! /usr/bin/env perl
2# Copyright 2023-2024 The OpenSSL Project Authors. All Rights Reserved.
3#
4# Licensed under the Apache License 2.0 (the "License").  You may not use
5# this file except in compliance with the License.  You can obtain a copy
6# in the file LICENSE in the source distribution or at
7# https://www.openssl.org/source/license.html
8
9
10use strict;
11use warnings;
12
13use File::Spec;
14use OpenSSL::Test qw(:DEFAULT pipe);
15use OpenSSL::Test::Utils;
16
17# These are special key generation tests for SM2 keys specifically,
18# as they could be said to be a bit special in their encoding.
19# This is an auxiliary test to 15-test_genec.t
20
21setup("test_gensm2");
22
23plan skip_all => "This test is unsupported in a no-sm2 build"
24    if disabled("sm2");
25
26plan tests => 2;
27
28# According to the example in  GM/T 0015-2012, appendix D.2,
29# generating an EC key with the named SM2 curve or generating
30# an SM2 key should end up with the same encoding (apart from
31# key private key field itself).  This regular expressions
32# shows us what 'openssl asn1parse' should display.
33
34my $sm2_re = qr|
35   ^
36   .*?\Qcons: SEQUENCE\E\s+?\R
37   .*?\Qprim:  INTEGER           :00\E\R
38   .*?\Qcons:  SEQUENCE\E\s+?\R
39   .*?\Qprim:   OBJECT            :id-ecPublicKey\E\R
40   .*?\Qprim:   OBJECT            :sm2\E\R
41   .*?\Qprim:  OCTET STRING      [HEX DUMP]:\E
42   |mx;
43
44my $cmd_genec = app([ 'openssl', 'genpkey',
45                      '-algorithm', 'EC',
46                      '-pkeyopt', 'ec_paramgen_curve:SM2',
47                      '-pkeyopt', 'ec_param_enc:named_curve' ]);
48my $cmd_gensm2 = app([ 'openssl', 'genpkey', '-algorithm', 'SM2' ]);
49my $cmd_asn1parse = app([ 'openssl', 'asn1parse', '-i' ]);
50
51my $result_ec = join("", run(pipe($cmd_genec, $cmd_asn1parse),
52                             capture => 1));
53
54like($result_ec, $sm2_re,
55     "Check that 'genpkey -algorithm EC' resulted in a correctly encoded SM2 key");
56
57my $result_sm2 = join("", run(pipe($cmd_gensm2, $cmd_asn1parse),
58                              capture => 1));
59
60like($result_sm2, $sm2_re,
61     "Check that 'genpkey -algorithm SM2' resulted in a correctly encoded SM2 key");
62