3030//
3131// ******************************************************************************************************************************
3232
33-
33+ using System . Security . Cryptography ;
3434using System . Security . Cryptography . X509Certificates ;
3535
3636namespace InterlockLedger . Tags ;
37+
3738public static class X509Certificate2Extensions
3839{
39- public static KeyStrength KeyStrengthGuess ( this X509Certificate2 certificate )
40- => certificate . Required ( ) . GetRSAPublicKey ( ) . KeyStrengthGuess ( ) ;
40+ public static ( KeyStrength keyStrength , Algorithm algorithm ) IdentifyAttributes ( this X509Certificate2 certificate ) =>
41+ certificate . Selector (
42+ ( rsa ) => ( rsa . KeyStrengthGuess ( ) , Algorithm . RSA ) ,
43+ ( ec ) => ( KeyStrength . Strong , Algorithm . EcDSA ) ,
44+ ( ) => ( KeyStrength . Normal , Algorithm . Invalid ) ) ;
45+
46+ public static TagPubKey PubKey ( this X509Certificate2 certificate ) =>
47+ certificate . Selector < TagPubKey > (
48+ ( rsa ) => new TagPubRSAKey ( rsa . ExportParameters ( false ) ) ,
49+ ( ec ) => new TagPubEcDSAKey ( ec . ExportParameters ( false ) ) ) ;
4150
42- public static TagPubKey PubKey ( this X509Certificate2 certificate )
43- => TagPubKey . Resolve ( certificate ) ;
44- }
51+ private static T Selector < T > ( this X509Certificate2 certificate ,
52+ Func < RSA , T > rsaFunc ,
53+ Func < ECDsa , T > ecdsaFunc ,
54+ Func < T > ? errorFunc = null ) =>
55+ certificate . GetRSAPublicKey ( ) switch {
56+ RSA rsa => rsaFunc ( rsa ) ,
57+ _ => certificate . GetECDsaPublicKey ( ) switch {
58+ ECDsa ec => ecdsaFunc ( ec ) ,
59+ _ => errorFunc is null
60+ ? throw new NotSupportedException ( "Not yet supporting other kinds of certificates, than RSA and EcDSA!" )
61+ : errorFunc ( )
62+ }
63+ } ;
64+ }
0 commit comments