码迷,mamicode.com
首页 > 编程语言 > 详细

关于RSA加密算法的长度问题

时间:2015-06-10 14:19:29      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

RSA是常用的非对称加密算法。近来有学生在项目中使用System.Security类库中的RSA加密算法时,出现了“不正确的长度”,这实际上是因为待加密的数据超长所致。.net

Framework中提供的RSA算法规定,每次加密的字节数,不能超过密钥的长度值减去11,而每次加密得到的密文长度,却恰恰是密钥的长度。所以,如果要加密较长的数据,可以采用数据截取的方法,分段加密。或者增加自定义分块算法,进行加密。当然,你也可以加长密钥的长度,呵呵。下面是分段加解密代码片段,希望对程序媛们有帮助


public override byte[] Encrypt(byte[] sourceBytes)
        {
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = KeyContainerName;
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(cspParams);

            int keySize = RSAalg.KeySize / 8;
            int bufferSize = keySize - 11;
            byte[] buffer = new  byte[bufferSize];
            MemoryStream msInput = new MemoryStream(sourceBytes);
            MemoryStream msOutput = 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 = RSAalg.Encrypt(dataToEnc, false);

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

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

            }

            msInput.Close();

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

            msOutput.Close();

            RSAalg.Clear();

            return result;

            //return RSAalg.Encrypt(sourceBytes, false);
        }

        public override byte[] Decrypt(byte[] cryptBytes)
        {
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = KeyContainerName;
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(cspParams);
            //return RSAalg.Decrypt(cryptBytes, false);
            int keySize = RSAalg.KeySize / 8;
            int bufferSize = keySize;// keySize - 11;
            byte[] buffer = new byte[bufferSize];
            MemoryStream msInput = new MemoryStream(cryptBytes);
            MemoryStream msOutput = new MemoryStream();
            int readLen = msInput.Read(buffer, 0, bufferSize);
            while (readLen > 0)
            {

                byte[] dataToDec = new byte[readLen];

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

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

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

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

            }

            msInput.Close();

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

            msOutput.Close();

            RSAalg.Clear();

            return result;
        }


关于RSA加密算法的长度问题

标签:

原文地址:http://blog.csdn.net/nnsword/article/details/46439043

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!