public Encrypt ( byte data, RSAEncryptionPadding padding ) : byte[] | ||
data | byte | |
padding | RSAEncryptionPadding | |
return | byte[] |
using System.Security.Cryptography; // Generate a new RSA key pair using var rsa = new RSACryptoServiceProvider(2048); // Get the public key var publicKey = rsa.ExportParameters(false); // Get the private key var privateKey = rsa.ExportParameters(true); // Encrypt a message using the public key byte[] message = Encoding.UTF8.GetBytes("Hello, world!"); byte[] encryptedMessage = rsa.Encrypt(message, false); // Decrypt the message using the private key byte[] decryptedMessage = rsa.Decrypt(encryptedMessage, false); string result = Encoding.UTF8.GetString(decryptedMessage); Console.WriteLine(result); // Output: "Hello, world!"
using System.Security.Cryptography; // Create an RSA object with a 4096-bit key using var rsa = new RSACryptoServiceProvider(4096); // Open the file to encrypt byte[] data = File.ReadAllBytes("largefile.txt"); // Encrypt the file using the RSA object byte[] encryptedData = rsa.Encrypt(data, true); // Save the encrypted file File.WriteAllBytes("largefile.txt.encrypted", encryptedData);In this example, we use the RSACryptoServiceProvider to encrypt a large file. We create an RSA object with a 4096-bit key and use it to read in the contents of the large file into a byte array. We then encrypt the byte array using RSA and save the encrypted data to a new file. Package library: The RSACryptoServiceProvider is part of the .NET framework, which is included with Microsoft Visual Studio and can be found in the System.Security.Cryptography namespace.
public Encrypt ( byte data, RSAEncryptionPadding padding ) : byte[] | ||
data | byte | |
padding | RSAEncryptionPadding | |
return | byte[] |