11use base64:: prelude:: * ;
22use openssl:: { pkey:: Public , rsa:: Rsa } ;
3+ use thiserror:: Error ;
4+
5+ /// Errors that can occur during RSA key parsing
6+ #[ derive( Error , Debug , Clone ) ]
7+ pub enum RsaParseError {
8+ #[ error( "Unable to decode base64 PEM data: {0}" ) ]
9+ Base64Decode ( #[ from] base64:: DecodeError ) ,
10+
11+ #[ error( "Unable to convert decoded PEM data into a string: {0}" ) ]
12+ Utf8Conversion ( #[ from] std:: string:: FromUtf8Error ) ,
13+
14+ #[ error( "Failed to parse RSA public key: {source}" ) ]
15+ RsaParsing {
16+ #[ source]
17+ source : openssl:: error:: ErrorStack ,
18+ } ,
19+ }
20+
21+ impl From < RsaParseError > for String {
22+ fn from ( error : RsaParseError ) -> Self {
23+ error. to_string ( )
24+ }
25+ }
326
427// Parse from a RSA public key string into the associated RSA representation
5- pub fn parse_rsa ( pem_data : & str ) -> Result < Rsa < Public > , String > {
28+ pub fn parse_rsa ( pem_data : & str ) -> Result < Rsa < Public > , RsaParseError > {
629 // First decode the base64 data
7- let pem_decoded = BASE64_STANDARD
8- . decode ( pem_data)
9- . map_err ( |e| format ! ( "Unable to decode base64 pem data: {e}" ) ) ?;
30+ let pem_decoded = BASE64_STANDARD . decode ( pem_data) ?;
1031
1132 // Convert the decoded data to a string
12- let mut pem_string = String :: from_utf8 ( pem_decoded)
13- . map_err ( |e| format ! ( "Unable to convert decoded pem data into a string: {e}" ) ) ?;
33+ let mut pem_string = String :: from_utf8 ( pem_decoded) ?;
1434
1535 // Fix the header - replace PKCS1 header with PKCS8 header
1636 pem_string = pem_string
@@ -22,7 +42,7 @@ pub fn parse_rsa(pem_data: &str) -> Result<Rsa<Public>, String> {
2242
2343 // Parse the PEM string into an RSA public key using PKCS8 format
2444 let rsa_pubkey = Rsa :: public_key_from_pem ( pem_string. as_bytes ( ) )
25- . map_err ( |e| format ! ( "Failed to parse RSA public key: {e}" ) ) ?;
45+ . map_err ( |source| RsaParseError :: RsaParsing { source } ) ?;
2646
2747 Ok ( rsa_pubkey)
2848}
0 commit comments