在.Net中,您可以这样创建密钥对:
public static Tuple<string, string> CreateKeyPair(){ CspParameters cspParams = new CspParameters { ProviderType = 1 }; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams); string publicKey = Convert.Tobase64String(rsaProvider.ExportCspBlob(false)); string privateKey = Convert.Tobase64String(rsaProvider.ExportCspBlob(true)); return new Tuple<string, string>(privateKey, publicKey);}然后,您可以使用公共密钥对消息进行加密,如下所示:
public static byte[] Encrypt(string publicKey, string data){ CspParameters cspParams = new CspParameters { ProviderType = 1 }; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.importCspBlob(Convert.Frombase64String(publicKey)); byte[] plainBytes = Encoding.UTF8.GetBytes(data); byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false); return encryptedBytes;}并使用私钥像这样解密:
public static string Decrypt(string privateKey, byte[] encryptedBytes){ CspParameters cspParams = new CspParameters { ProviderType = 1 }; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.importCspBlob(Convert.Frombase64String(privateKey)); byte[] plainBytes = rsaProvider.Decrypt(encryptedBytes, false); string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length); return plainText;}


