xref: /openssl/test/recipes/91-test_pkey_check.t (revision 08e0aad2)
1#! /usr/bin/env perl
2# Copyright 2017-2021 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 data_file/;
15use OpenSSL::Test::Utils;
16
17sub pkey_check {
18    my $f = shift;
19
20    return run(app(['openssl', 'pkey', '-check', '-text',
21                    '-in', $f]));
22}
23
24sub check_key {
25    my $f = shift;
26    my $should_fail = shift;
27    my $str;
28
29
30    $str = "$f should fail validation" if $should_fail;
31    $str = "$f should pass validation" unless $should_fail;
32
33    $f = data_file($f);
34
35    if ( -s $f ) {
36        if ($should_fail) {
37            ok(!pkey_check($f), $str);
38        } else {
39            ok(pkey_check($f), $str);
40        }
41    } else {
42        fail("Missing file $f");
43    }
44}
45
46setup("test_pkey_check");
47
48my @negative_tests = ();
49
50push(@negative_tests, (
51    # For EC keys the range for the secret scalar `k` is `1 <= k <= n-1`
52    "ec_p256_bad_0.pem", # `k` set to `n` (equivalent to `0 mod n`, invalid)
53    "ec_p256_bad_1.pem", # `k` set to `n+1` (equivalent to `1 mod n`, invalid)
54    )) unless disabled("ec");
55
56push(@negative_tests, (
57    # For SM2 keys the range for the secret scalar `k` is `1 <= k < n-1`
58    "sm2_bad_neg1.pem", # `k` set to `n-1` (invalid, because SM2 range)
59    "sm2_bad_0.pem", # `k` set to `n` (equivalent to `0 mod n`, invalid)
60    "sm2_bad_1.pem", # `k` set to `n+1` (equivalent to `1 mod n`, invalid)
61    )) unless disabled("sm2");
62
63my @positive_tests = ();
64
65push(@positive_tests, (
66    "dhpkey.pem"
67    )) unless disabled("dh");
68
69plan skip_all => "No tests within the current enabled feature set"
70    unless @negative_tests && @positive_tests;
71
72plan tests => scalar(@negative_tests) + scalar(@positive_tests);
73
74foreach my $t (@negative_tests) {
75    check_key($t, 1);
76}
77
78foreach my $t (@positive_tests) {
79    check_key($t, 0);
80}
81