@@ -85,22 +85,39 @@ public static unsafe void Convert(this Encoder encoder, ReadOnlySpan<char> chars
85
85
/// <returns>An RSA key.</returns>
86
86
public static RSAParameters GetRsaParameters ( string key )
87
87
{
88
+ const string beginRsaPrivateKey = "-----BEGIN RSA PRIVATE KEY-----" ;
89
+ const string endRsaPrivateKey = "-----END RSA PRIVATE KEY-----" ;
90
+ const string beginPublicKey = "-----BEGIN PUBLIC KEY-----" ;
91
+ const string endPublicKey = "-----END PUBLIC KEY-----" ;
92
+
93
+ int keyStartIndex ;
94
+ string pemFooter ;
88
95
bool isPrivate ;
89
- if ( key . StartsWith ( "-----BEGIN RSA PRIVATE KEY-----" , StringComparison . Ordinal ) )
96
+
97
+ if ( ( keyStartIndex = key . IndexOf ( beginRsaPrivateKey , StringComparison . Ordinal ) ) > - 1 )
90
98
{
91
- key = key . Replace ( "-----BEGIN RSA PRIVATE KEY-----" , "" ) . Replace ( "-----END RSA PRIVATE KEY-----" , "" ) ;
99
+ keyStartIndex += beginRsaPrivateKey . Length ;
100
+ pemFooter = endRsaPrivateKey ;
92
101
isPrivate = true ;
93
102
}
94
- else if ( key . StartsWith ( "-----BEGIN PUBLIC KEY-----" , StringComparison . Ordinal ) )
103
+ else if ( ( keyStartIndex = key . IndexOf ( beginPublicKey , StringComparison . Ordinal ) ) > - 1 )
95
104
{
96
- key = key . Replace ( "-----BEGIN PUBLIC KEY-----" , "" ) . Replace ( "-----END PUBLIC KEY-----" , "" ) ;
105
+ keyStartIndex += beginPublicKey . Length ;
106
+ pemFooter = endPublicKey ;
97
107
isPrivate = false ;
98
108
}
99
109
else
100
110
{
101
111
throw new FormatException ( "Unrecognized PEM header: " + key . Substring ( 0 , Math . Min ( key . Length , 80 ) ) ) ;
102
112
}
103
113
114
+ var keyEndIndex = key . IndexOf ( pemFooter , keyStartIndex , StringComparison . Ordinal ) ;
115
+
116
+ if ( keyEndIndex <= - 1 )
117
+ throw new FormatException ( $ "Missing expected '{ pemFooter } ' PEM footer: " + key . Substring ( Math . Max ( key . Length - 80 , 0 ) ) ) ;
118
+
119
+ key = key . Substring ( keyStartIndex , keyEndIndex - keyStartIndex ) ;
120
+
104
121
return GetRsaParameters ( System . Convert . FromBase64String ( key ) , isPrivate ) ;
105
122
}
106
123
0 commit comments