/// <summary>Encrypt text using a public key</summary> public static string Encrypt(string plainText, RSAKeyValues key) { // validate input if (!IsKeySizeValid((int)key.KeySize)) { throw new ArgumentException("Key size is not valid", "keySize"); } if (String.IsNullOrEmpty(plainText)) { throw new ArgumentException("Nothing to encrypt", "plainText"); } int maxLength = GetMaxDataLength((int)key.KeySize); byte[] data = Encoding.UTF8.GetBytes(plainText); if (data.Length > maxLength) { throw new ArgumentException($"Maximum data length is {maxLength}.", "data"); } using var provider = new RSACryptoServiceProvider((int)key.KeySize); provider.ImportParameters(key.Parameters); byte[] encdata = provider.Encrypt(data, OptimalAsymmetricEncryptionPadding); return(Convert.ToBase64String(encdata)); }
/// <summary>Decrypt using the private key</summary> public static string Decrypt(string encryptedText, RSAKeyValues key) { // validate input if (!IsKeySizeValid((int)key.KeySize)) { throw new ArgumentException("Key size is not valid", "keySize"); } byte[] encdata = Convert.FromBase64String(encryptedText); using var provider = new RSACryptoServiceProvider((int)key.KeySize); provider.ImportParameters(key.Parameters); byte[] data = provider.Decrypt(encdata, OptimalAsymmetricEncryptionPadding); return(Encoding.UTF8.GetString(data)); }
/// <summary>Signs some data with the specified private asym key using SHA-256</summary> /// <param name="data"></param> /// <returns></returns> public static byte[] SignWithSHA256(byte[] data, RSAKeyValues key) { if (data == null || data.Length < 1) { throw new ArgumentException("Nothing to sign.", "data"); } // validate input if (!IsKeySizeValid((int)key.KeySize)) { throw new ArgumentException("Key size is not valid", "keySize"); } using var provider = new RSACryptoServiceProvider((int)key.KeySize); provider.ImportParameters(key.Parameters); byte[] sig = provider.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); return(sig); }