csharp 发送RSA256加密消息 python接收并解密的代码
时间: 2023-05-16 17:06:29 浏览: 105
以下是C#发送RSA256加密消息Python接收并解密的代码:
C#代码:
```csharp
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string publicKey = "<RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>";
string privateKey = "<RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent><P>...</P><Q>...</Q><DP>...</DP><DQ>...</DQ><InverseQ>...</InverseQ><D>...</D></RSAKeyValue>";
string message = "Hello, Python!";
byte[] encrypted = Encrypt(message, publicKey);
Console.WriteLine("Encrypted message: " + Convert.ToBase64String(encrypted));
string decrypted = Decrypt(encrypted, privateKey);
Console.WriteLine("Decrypted message: " + decrypted);
}
static byte[] Encrypt(string message, string publicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
byte[] data = Encoding.UTF8.GetBytes(message);
byte[] encrypted = rsa.Encrypt(data, true);
return encrypted;
}
static string Decrypt(byte[] encrypted, string privateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(privateKey);
byte[] decrypted = rsa.Decrypt(encrypted, true);
string message = Encoding.UTF8.GetString(decrypted);
return message;
}
}
```
Python代码:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
public_key = """<RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>"""
private_key = """<RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent><P>...</P><Q>...</Q><DP>...</DP><DQ>...</DQ><InverseQ>...</InverseQ><D>...</D></RSAKeyValue>"""
message = "Hello, Python!".encode("utf-8")
public_key = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(public_key)
encrypted = cipher.encrypt(message)
print("Encrypted message: " + base64.b64encode(encrypted).decode("utf-8"))
private_key = RSA.importKey(private_key)
cipher = PKCS1_v1_5.new(private_key)
decrypted = cipher.decrypt(encrypted, None).decode("utf-8")
print("Decrypted message: " + decrypted)
```