/// <summary> /// Creates a X509-formatted public key string from a given RSA key pair. /// </summary> public static string GetPublicKeyFormattedString(RSA keyPair) { var publicKey = keyPair.ExportParameters(false); var publicKeyBytes = RsaKeyUtils.PublicKeyToX509(publicKey); return(string.Format(FORMAT_PUBLIC_KEY, Convert.ToBase64String(publicKeyBytes))); }
/// <summary> /// Creates a public-key-only RSA key pair from X509-formatted public key string. /// </summary> public static RSA CreatePublicKeyFromPublicKeyFormattedString(string publicKeyString) { var publicKeyStringTrimmed = publicKeyString .Replace(PUBLIC_KEY_START, string.Empty) .Replace(PUBLIC_KEY_END, string.Empty); return(RsaKeyUtils.DecodePublicKey(Convert.FromBase64String(publicKeyStringTrimmed))); }
/// <summary> /// Creates an RSA key pair from PKCS8-formatted private key string. /// </summary> public static RSA CreateKeyPairFromPrivateKeyFormattedString(string privateKeyString) { var privateKeyStringTrimmed = privateKeyString .Replace(PRIVATE_KEY_START, string.Empty) .Replace(PRIVATE_KEY_END, string.Empty); return(RsaKeyUtils.DecodePrivateKeyInfo(Convert.FromBase64String(privateKeyStringTrimmed))); }
/// <summary> /// Creates an RSA key pair from PKCS8-formatted RSA private key string. /// </summary> public static RSA CreateKeyPairFromRsaPrivateKeyFormattedString(string privateKeyString) { var privateKeyStringTrimmed = privateKeyString .Replace("-----BEGIN RSA PRIVATE KEY-----\n", "") .Replace("\n-----END RSA PRIVATE KEY-----\n", ""); return(RsaKeyUtils.DecodeRsaPrivateKey(Convert.FromBase64String(privateKeyStringTrimmed))); }
/// <summary> /// Creates an RSA key pair from PKCS8-formatted RSA private key string. /// </summary> public static RSA CreateKeyPairFromRsaPrivateKeyFormattedString(string privateKeyString) { var privateKeyStringTrimmed = privateKeyString .Replace(WINDOWS_NEWLINE, NEWLINE) .Replace(RSA_PRIVATE_KEY_START, String.Empty) .Replace(RSA_PRIVATE_KEY_END, String.Empty) .Trim(); return(RsaKeyUtils.DecodeRsaPrivateKey(Convert.FromBase64String(privateKeyStringTrimmed))); }
/// <summary> /// If possible, creates a PKCS8-formatted private key string from a given RSA key pair; else returns an empty /// string. /// </summary> public static string GetPrivateKeyFormattedString(RSA keyPair) { try { var privateKey = keyPair.ExportParameters(true); var privateKeyBytes = RsaKeyUtils.PrivateKeyToPkcs8(privateKey); return(string.Format(FORMAT_PRIVATE_KEY, Convert.ToBase64String(privateKeyBytes))); } catch (SecurityException) { return(string.Empty); } }