关于JAVA和C#加解密通讯的话,可以用这个BouncyCastle插件,会帮助你解决很多问题
//c#使用java给的公钥进行rsa加密
public static byte[] RSAEncrypt(string publickey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] publicKeyBytes = Convert.FromBase64String(publickey);
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
rsa.ImportParameters(rsaParameters);
return rsa.Encrypt(Encoding.GetEncoding("gbk").GetBytes(content), false);
}
使用方法:
string tempStr=Convert.ToBase64String(RSACoder.RSAEncrypt("公钥", "需要加密码的字符"))
另一种写法:一般都是参数使用utf-8编码:
public string RSAEncrypt2(string publickey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] publicKeyBytes = Convert.FromBase64String(publickey);
AsymmetricKeyParameter privateKey = PublicKeyFactory.CreateKey(publicKeyBytes);
IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
//加密
c.Init(true, privateKey);
byte[] byteData = Encoding.UTF8.GetBytes(content);
byteData = c.DoFinal(byteData, , byteData.Length);
return Convert.ToBase64String(byteData);
}
c#通过rsa公钥解密java那边加密字符:
public static string RSADeEncry222(string content, string publickey)
{
byte[] btPem = Convert.FromBase64String(publickey);
int pemModulus = , pemPublicExponent = ;
byte[] btPemModulus = new byte[];
byte[] btPemPublicExponent = new byte[];
for (int i = ; i < pemModulus; i++)
{
btPemModulus[i] = btPem[ + i];
}
for (int i = ; i < pemPublicExponent; i++)
{
btPemPublicExponent[i] = btPem[ + i];
}
BigInteger biModulus = new BigInteger(, btPemModulus);
BigInteger biExponent = new BigInteger(, btPemPublicExponent);
RsaKeyParameters publicParameters = new RsaKeyParameters(false, biModulus, biExponent);
IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(false, publicParameters);
// 解密已加密的数据
byte[] encryptedData = Convert.FromBase64String(content);
encryptedData = eng.ProcessBlock(encryptedData, , encryptedData.Length);
string result = Encoding.UTF8.GetString(encryptedData, , encryptedData.Length);
return result;
}
普通C#自身调用加解密:
RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
string privatekey = oRSA.ToXmlString(true);//私钥
string publickey = oRSA.ToXmlString(false);//公钥
//这两个密钥需要保存下来
byte[] messagebytes = Encoding.UTF8.GetBytes("luo罗"); //需要加密的数据 //公钥加密
RSACryptoServiceProvider oRSA1 = new RSACryptoServiceProvider();
oRSA1.FromXmlString(publickey); //加密要用到公钥所以导入公钥
byte[] AOutput = oRSA1.Encrypt(messagebytes, false); //AOutput 加密以后的数据 //私钥解密
RSACryptoServiceProvider oRSA2 = new RSACryptoServiceProvider();
oRSA2.FromXmlString(privatekey);
byte[] AInput = oRSA2.Decrypt(AOutput, false);
string reslut = Encoding.UTF8.GetString(AInput);