本段代码展示了如何使用C#编程语言实现利用RSA算法进行数据加密与解密的过程。具体来说,它演示了通过私钥加密信息以及使用对应的公钥来解密这些信息的方法,为开发者提供了基于RSA非对称加密技术的实际应用示例。
C# RSA私钥加密与公钥解密的源码实现如下:
```csharp
using System;
using System.Security.Cryptography;
public class RsaEncryptionExample {
public static void Main() {
string originalValue = Hello, World!;
// 生成RSA密钥对
using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider()) {
Console.WriteLine(私钥: + rsaProvider.ToXmlString(true));
Console.WriteLine(公钥: + rsaProvider.ToXmlString(false));
string encryptedValue = EncryptWithPublicKey(originalValue, rsaProvider);
string decryptedValue = DecryptWithPrivateKey(encryptedValue, rsaProvider);
Console.WriteLine($原始值:{originalValue});
Console.WriteLine($加密后:{Convert.ToBase64String(Encoding.UTF8.GetBytes(encryptedValue))});
Console.WriteLine($解密后:{decryptedValue});
}
}
public static string EncryptWithPublicKey(string plainText, RSACryptoServiceProvider rsa) {
byte[] data = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(rsa.Encrypt(data, false));
}
public static string DecryptWithPrivateKey(string cipherText, RSACryptoServiceProvider rsa) {
byte[] encryptedData = Convert.FromBase64String(cipherText);
byte[] decryptedData = rsa.Decrypt(encryptedData, true);
return Encoding.UTF8.GetString(decryptedData);
}
}
```
这段代码展示了如何使用C#中的RSA算法进行私钥加密和公钥解密。首先生成一个RSA密钥对,然后用公钥来加密原始文本,并利用私钥解密得到的密文以恢复原来的明文信息。