public static void FromPkcs1PublicString(this RSA rsa, string publicKey, out RSAParameters parameters) { publicKey = RSAPemFormatHelper.Pkcs1PublicKeyFormatRemove(publicKey); var pr = new PemReader(new StringReader(publicKey)); if (!(pr.ReadObject() is RsaKeyParameters rsaKey)) { throw new Exception("Public key format is incorrect"); } parameters = new RSAParameters { Modulus = rsaKey.Modulus.ToByteArrayUnsigned(), Exponent = rsaKey.Exponent.ToByteArrayUnsigned() }; rsa.ImportParameters(parameters); }
/// <summary> /// Import RSA public key /// </summary> /// <param name="rsa"></param> /// <param name="type"></param> /// <param name="publicKey"></param> /// <param name="isPem"></param> public static void ImportPublicKey(this RSA rsa, RSAKeyTypes type, string publicKey, bool isPem = false) { if (isPem) { publicKey = type switch { RSAKeyTypes.XML => publicKey, RSAKeyTypes.JSON => publicKey, RSAKeyTypes.Pkcs1 => RSAPemFormatHelper.Pkcs1PublicKeyFormatRemove(publicKey), RSAKeyTypes.Pkcs8 => RSAPemFormatHelper.Pkcs8PublicKeyFormatRemove(publicKey), _ => throw new NotSupportedException("Unknown RSA key type.") }; } switch (type) { case RSAKeyTypes.XML: rsa.FromLvccXmlString(publicKey); break; case RSAKeyTypes.JSON: rsa.FromJsonString(publicKey); break; case RSAKeyTypes.Pkcs1: #if NETCOREAPP3_1 || NETSTANDARD2_1 rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out _); break; #else rsa.FromPkcs1PublicString(publicKey, out _); break; #endif case RSAKeyTypes.Pkcs8: #if NETCOREAPP3_1 || NETSTANDARD2_1 rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out _); break; #else rsa.FromPkcs8PublicString(publicKey, out _); break; #endif } }