1#! /usr/bin/env perl 2# Copyright 2017-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 data_file with/; 15use OpenSSL::Test::Utils; 16 17sub pkey_check { 18 my $f = shift; 19 my $pubcheck = shift; 20 my @checkopt = ('-check'); 21 22 @checkopt = ('-pubcheck', '-pubin') if $pubcheck; 23 24 return run(app(['openssl', 'pkey', @checkopt, '-text', 25 '-in', $f])); 26} 27 28sub check_key { 29 my $f = shift; 30 my $should_fail = shift; 31 my $pubcheck = shift; 32 my $str; 33 34 35 $str = "$f should fail validation" if $should_fail; 36 $str = "$f should pass validation" unless $should_fail; 37 38 $f = data_file($f); 39 40 if ( -s $f ) { 41 with({ exit_checker => sub { return shift == $should_fail; } }, 42 sub { 43 ok(pkey_check($f, $pubcheck), $str); 44 }); 45 } else { 46 fail("Missing file $f"); 47 } 48} 49 50setup("test_pkey_check"); 51 52my @negative_tests = (); 53 54push(@negative_tests, ( 55 # For EC keys the range for the secret scalar `k` is `1 <= k <= n-1` 56 "ec_p256_bad_0.pem", # `k` set to `n` (equivalent to `0 mod n`, invalid) 57 "ec_p256_bad_1.pem", # `k` set to `n+1` (equivalent to `1 mod n`, invalid) 58 )) unless disabled("ec"); 59 60push(@negative_tests, ( 61 # For SM2 keys the range for the secret scalar `k` is `1 <= k < n-1` 62 "sm2_bad_neg1.pem", # `k` set to `n-1` (invalid, because SM2 range) 63 "sm2_bad_0.pem", # `k` set to `n` (equivalent to `0 mod n`, invalid) 64 "sm2_bad_1.pem", # `k` set to `n+1` (equivalent to `1 mod n`, invalid) 65 )) unless disabled("sm2"); 66 67my @positive_tests = (); 68 69push(@positive_tests, ( 70 "dhpkey.pem" 71 )) unless disabled("dh"); 72 73my @negative_pubtests = ("rsapub_17k.pem"); # Too big RSA public key 74 75push(@negative_pubtests, ( 76 "dsapub_noparam.der" 77 )) unless disabled("dsa"); 78 79my @positive_pubtests = (); 80 81push(@positive_pubtests, ( 82 "dsapub.pem" 83 )) unless disabled("dsa"); 84 85plan skip_all => "No tests within the current enabled feature set" 86 unless @negative_tests && @positive_tests 87 && @negative_pubtests && @positive_pubtests; 88 89plan tests => scalar(@negative_tests) + scalar(@positive_tests) 90 + scalar(@negative_pubtests) + scalar(@positive_pubtests); 91 92foreach my $t (@negative_tests) { 93 check_key($t, 1, 0); 94} 95 96foreach my $t (@positive_tests) { 97 check_key($t, 0, 0); 98} 99 100foreach my $t (@negative_pubtests) { 101 check_key($t, 1, 1); 102} 103 104foreach my $t (@positive_pubtests) { 105 check_key($t, 0, 1); 106} 107