RSA 加解密

        #region RSA
public static byte[] GetBytes(String num)
{
BigInteger n = new BigInteger(num, );
String s = n.ToString();
if (s.Length % > )
{
s = new String('', - s.Length % ) + s;
}
byte[] data = new byte[s.Length / ];
String ocetstr;
for (int i = ; i < data.Length; i++)
{
ocetstr = s.Substring( * i, );
data[i] = Convert.ToByte(ocetstr, );
}
return data;
} /// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static String ConvByteArrayToHex(byte[] data)
{
String s = "";
for (int i = ; i < data.Length; i++)
{
s += Convert.ToString(data[i], );
}
return s.ToUpper();
}
public static string RSAEncrypt(string Modulus, string Exponent, string content)
{
var param = new RSAParameters();
param.Exponent = GetBytes(Exponent);
param.Modulus = GetBytes(Modulus);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(param); int CellLength = new BigInteger(param.Modulus).bitCount() / ; byte[] bInput = Encoding.UTF8.GetBytes(content); int MaxLength = CellLength - ;
int GroupLength = (int)Math.Ceiling(bInput.Length * 1.00 / MaxLength); byte[] cipherText = new byte[GroupLength * CellLength];
for (int i = ; i < GroupLength; i++)
{
int len = MaxLength < bInput.Length - MaxLength * i ? MaxLength
: bInput.Length - MaxLength * i;
byte[] inByte = new byte[len];
Buffer.BlockCopy(bInput, MaxLength * i, inByte, , len); byte[] temp = rsa.Encrypt(inByte, false);
Buffer.BlockCopy(temp, , cipherText, i * CellLength, CellLength);
}
//cipherText = rsa.Encrypt(bInput, false);
//return Convert.ToBase64String(cipherText);
//return toHex(cipherText);
return BitConverter.ToString(cipherText).Replace("-", ""); } #endregion
上一篇:vim编辑下Python2.0自动补全


下一篇:pickle使用及案例