ict.lixian.three/Assets/Scripts/cxx/call/RSAPro.cs

67 lines
2.2 KiB
C#

using UnityEngine;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
public class RSAPro
{
string publickey;
string privatekey;
string RSAed;
public string mingwen;
RSACryptoServiceProvider rsa;
/// <summary>
/// 加密
/// </summary>
/// <param name="publickey">公钥</param>
/// <param name="content">所加密的内容</param>
/// <returns>加密后的内容</returns>
public static string RSAEncrypt(string publickey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(publickey);
//rsa.FromXmlString("<param name='publickey'>"+publickey+"</param>");
cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
return Convert.ToBase64String(cipherbytes); ;
}
/// <summary>
/// 解密
/// </summary>
/// <param name="privatekey">私钥</param>
/// <param name="content">加密后的内容</param>
/// <returns>解密后的内容</returns>
public static string RSADecrypt(string privatekey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(privatekey);
cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
return Encoding.UTF8.GetString(cipherbytes);
}
/// <summary>
/// base64 public key string -> xml public key
/// </summary>
/// <param name="pubilcKey"></param>
/// <returns></returns>
public static string ToXmlPublicKey(string pubilcKey)
{
RsaKeyParameters p =PublicKeyFactory.CreateKey(Convert.FromBase64String(pubilcKey)) as RsaKeyParameters;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
RSAParameters rsaParams = new RSAParameters
{
Modulus = p.Modulus.ToByteArrayUnsigned(),
Exponent = p.Exponent.ToByteArrayUnsigned()
};
rsa.ImportParameters(rsaParams);
return rsa.ToXmlString(false);
}
}
}