呵呵呵呵呵

萝莉有三好,柔体 轻音 易推倒。女神有三宝,干嘛 呵呵 去洗澡。宅男有三好:Dota 基友 破电脑。


C# RSA加密算法加密长度限制及任意长度数据加解密实现方法

C# RSA加密算法加密长度限制及任意长度数据加解密实现方法

RSA是常用的非对称加密算法。近来有学生在项目中使用System.Security类库中的RSA加密算法时,出现了“不正确的长度”,这实际上是因为待加密的数据超长所致。.net
Framework中提供的RSA算法规定,每次加密的字节数,不能超过密钥的长度值减去11,而每次加密得到的密文长度,却恰恰是密钥的长度。所以,如果要加密较长的数据,可以采用数据截取的方法,分段加密,实现如下:

       RSACryptoServiceProvider rsa = new
RSACryptoServiceProvider();

       byte[] data = ........;        
//要加密的数据

       string publicKey = .... ;  //获取公钥

       rsa.FromXmlString(publicKey);

       int keySize = rsa.KeySize / 8;

       int bufferSize = keySize - 11;

       byte[] buffer = new
byte[bufferSize];

       MemoryStream msInput = new
MemoryStream(data);

       MemoryStream msOuput = new
MemoryStream();

       int readLen = msInput.Read(buffer, 0,
bufferSize);

       while(readLen > 0)

       {

               byte[] dataToEnc = new
byte[readLen];

               Array.Copy(buffer, 0 , dataToEnc,
0, readLen);

               byte[] encData =
rsa.Encrypt(dataToEnc , false);

               msOutput.Write(encData, 0,
encData.Length);

               readLen = msInput.Read(buffer, 0,
bufferSize);

       }

       msInput.Close();

       byte[] result = msOutput.ToArray();   
//得到加密结果

       msOutput.Close();

       rsa.Clear();


解密时肯定也要使用分段解密,算法如下:

       RSACryptoServiceProvider rsa = new
RSACryptoServiceProvider();

       byte[] key = .....;    //加载私钥
       string privateKey =
Encoding.ASCII.GetString(key);
       byte[] dataEnc = ...;   //加载密文

       rsa.FromXmlString(privateKey);

       int keySize = rsa.KeySize / 8;

       byte[]
buffer = new byte[keySize];

       MemoryStream msInput = new
MemoryStream(dataEnc );

       MemoryStream msOuput = new
MemoryStream();

       int readLen = msInput.Read(buffer, 0,
keySize);

       while(readLen > 0)

       {

               byte[] dataToDec = new
byte[readLen];

               Array.Copy(buffer, 0 , dataToDec,
0, readLen);

               byte[] decData =
rsa.Decrypt(dataToDec , false);

               msOutput.Write(decData, 0,
decData.Length);

               readLen = msInput.Read(buffer, 0,
keySize);

       }

       msInput.Close();

       byte[] result = msOutput.ToArray();   
//得到解密结果

       msOutput.Close();

       rsa.Clear();

更多内容:

Windows 10将命令行cmd.exe恢复默认设置
C++ Builder2010 displayNotification:堆栈溢出
openssl rsa结合aes加解密相关的代码实现
用openssl命令行对文件加密及解密及命令行参数说明
windos批处理中的变量

本文链接地址:http://www.hehehehehe.cn/i/732.html