2
2
# Licensed under the MIT license.
3
3
4
4
import shlex
5
- from typing import TYPE_CHECKING
5
+ from typing import TYPE_CHECKING , Tuple
6
6
7
7
from lisa .executable import Tool
8
8
@@ -37,7 +37,7 @@ def encrypt(
37
37
return self ._run_with_piped_input (
38
38
plaintext ,
39
39
f"enc -{ algorithm } -K '{ hex_key } ' -iv '{ hex_iv } ' -base64 -A" ,
40
- expected_exit_code_failure_message = "Failed to encrypt data with OpenSSL." ,
40
+ expected_exit_code_failure_message = ( "Failed to encrypt data with OpenSSL." ) ,
41
41
)
42
42
43
43
def decrypt (
@@ -56,7 +56,69 @@ def decrypt(
56
56
return self ._run_with_piped_input (
57
57
ciphertext ,
58
58
f"enc -d -{ algorithm } -K '{ hex_key } ' -iv '{ hex_iv } ' -base64 -A" ,
59
- expected_exit_code_failure_message = "Failed to decrypt data with OpenSSL." ,
59
+ expected_exit_code_failure_message = ("Failed to decrypt data with OpenSSL." ),
60
+ )
61
+
62
+ def create_key_pair (self , algorithm : str = "RSA" ) -> Tuple [str , str ]:
63
+ """
64
+ Generate a key pair using the specified algorithm.
65
+ Returns the private key and public key as strings.
66
+
67
+ This key generation is for testing generation of keys
68
+ with OpenSSL on the remote.
69
+ """
70
+ private_key_result = self .run (
71
+ f"genpkey -algorithm { algorithm } -outform PEM" ,
72
+ expected_exit_code = 0 ,
73
+ expected_exit_code_failure_message = (
74
+ "Failed to generate private key with OpenSSL."
75
+ ),
76
+ )
77
+ private_key_pem = private_key_result .stdout .strip ()
78
+ public_key = self ._run_with_piped_input (
79
+ private_key_pem ,
80
+ "pkey -in /dev/stdin -pubout -outform PEM" ,
81
+ expected_exit_code_failure_message = (
82
+ "Failed to generate public key with OpenSSL."
83
+ ),
84
+ )
85
+ return private_key_pem , public_key
86
+
87
+ def sign (
88
+ self ,
89
+ data : str ,
90
+ private_key : str ,
91
+ algorithm : str = "sha256" ,
92
+ ) -> str :
93
+ """
94
+ Sign the data using the specified private key and algorithm.
95
+ Returns the base64 encoded signature.
96
+ """
97
+ return self ._run_with_piped_input (
98
+ data ,
99
+ f"dgst -{ algorithm } -sign <(echo '{ private_key } ') | openssl base64 -A" ,
100
+ expected_exit_code_failure_message = "Failed to sign data with OpenSSL." ,
101
+ )
102
+
103
+ def verify (
104
+ self ,
105
+ data : str ,
106
+ public_key : str ,
107
+ signature_base64 : str ,
108
+ algorithm : str = "sha256" ,
109
+ ) -> None :
110
+ """
111
+ Verify the signature of the data using the specified
112
+ public key and algorithm.
113
+ """
114
+ self ._run_with_piped_input (
115
+ data ,
116
+ f"dgst -{ algorithm } -verify <(echo '{ public_key } ') "
117
+ f"-signature <(echo '{ signature_base64 } ' | "
118
+ "openssl base64 -A -d)" ,
119
+ expected_exit_code_failure_message = (
120
+ "Failed to verify signature with OpenSSL."
121
+ ),
60
122
)
61
123
62
124
def _run_with_piped_input (
0 commit comments