public static void FromPemStringStd(this RSA @this, string pemString) { pemString = pemString.Replace("\r\n", string.Empty); string keyName; if (pemString.StartsWith("-----BEGIN PRIVATE KEY-----")) { keyName = "PRIVATE"; } else if (pemString.StartsWith("-----BEGIN PUBLIC KEY-----")) { keyName = "PUBLIC"; } else { throw new ArgumentException("Can't analyze Pem string."); } pemString = pemString .Replace($"-----BEGIN {keyName} KEY-----", string.Empty) .Replace($"-----END {keyName} KEY-----", string.Empty); var pem = Convert.FromBase64String(pemString); var @params = RsaConverter.ParamsFromPem(pem, keyName == "PRIVATE"); @this.ImportParameters(@params); }
public static string ToPemStringStd(this RSA @this, bool includePrivateParameters) { var keyName = includePrivateParameters ? "PRIVATE" : "PUBLIC"; var @params = @this.ExportParameters(includePrivateParameters); var base64 = string.Join(Environment.NewLine, Convert.ToBase64String( RsaConverter.ParamsToPem(@params, includePrivateParameters)) .ToCharArray().AsKvPairs() .GroupBy(x => x.Key / 64) .Select(g => new string(g.Select(x => x.Value).ToArray()))); return($"-----BEGIN {keyName} KEY-----\r\n{base64}\r\n-----END {keyName} KEY-----"); }