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();

posted on 2015-08-17 09:40  赵保龙  阅读(12247)  评论(0编辑  收藏  举报