在C#中有时用RSA加密并不是都要用一个完整的xml格式的key才能加密。其实也可以通过Exponent和Modulus参数来加密。exponent和modulus正好提供了一个公钥(只能用来加密)。
class Program
{
static void Main(string[] args)
{
string exponent = "010001";
string modulus =
"A3A69317FB92A534912A0999A7EEE826358C05F434C5E1E" +
"DB61C68E882CE52F7573FA44CE46E858673A8A328E17712F" +
"DAAECF383F13ECC1FD9D1505D2F23C983AD36F951788DEE30F1A" +
"E2A34F2DB13E46C409980A5467E05C7667AAD896464ABB073AA01AAF" +
"E130E28FA4D3D6A57ECA8422A482E22C5E0BA67434160B95A68DF";
RSAParameters rsaParameters = new RSAParameters()
{
Exponent = FromHex(exponent), // new byte[] {01, 00, 01}
Modulus = FromHex(modulus), // new byte[] {A3, A6, ...}
};
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
byte[] sample = rsa.Encrypt(Encoding.UTF8.GetBytes("hello world"), false);
}
static byte[] FromHex(string hex)
{
if (string.IsNullOrEmpty(hex) || hex.Length % 2 != 0) throw new ArgumentException("not a hexidecimal string");
List bytes = new List();
for (int i = 0; i < hex.Length; i += 2)
{
bytes.Add(Convert.ToByte(hex.Substring(i, 2), 16));
}
return bytes.ToArray();
}
}
RSAParameters Exponent 是三个字节,一般固定是0x01, 0, 0x01
byte[] plainData = new byte[117];// 明文数据;
RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
RSAParameters rparam = new RSAParameters();
rparam.Modulus = mods;
rparam.Exponent = new byte[] { 1, 0, 1 };
rsaPub.ImportParameters(rparam);
byte[] enData = rsaPub.Encrypt(plainData, false);
相关参考: