RSA加密大文件

时间:2013-04-28 17:25:23

标签: c# base64 rsa rsacryptoserviceprovider

问题是我使用rsa使用rsa加密了一个文件:

        for (int a = 0; a <= iterations; a++)
        {
            byte[] plain;
            int rsaLen = rsa.KeySize / 8 - 11;
            int bytesLen = plain.Length;
            int block = bytesLen - rsaLen * a;

            //The last block in the text may not be a full block
            if (block > rsaLen )
                plain = new byte[maxRsaLength];
            else
                plainblock = new byte[block];

            Buffer.BlockCopy(plaintext, rsaLen * a, plain, 0, plain.Length);

            //purfoming the encryption
            ciphertext.Append(Convert.ToBase64String(rsa.Encrypt(plain, false)));
        }

问题是,当我尝试解密时,我必须将我已经放入64位的密文转换为基本64块,但后来我从RSAServiceProvider的解密方法得到了一个糟糕的长度。我一直在关注这个网站上写的例子: http://digitalsquid.co.uk/2009/01/rsa-in-cs/无济于事。我解密时不会遇到任何加密错误。我甚至无法确定我是否已经完成了加密。贝娄是我的解密循环:

   public string Decrypt(string ciphertext, string key = null)
    {
        //checking for ciphertext. Exception raise if null
        if (String.IsNullOrEmpty(ciphertext)) throw new ArgumentNullException(ciphertext, "There is no ciphertext to decrypt.");

        //String holding the decrypted value
        string plaintext = String.Empty;

        //chanck is the user has provided a key. If not the use the one automatically generated
        string keyToUse = String.IsNullOrEmpty(key) ? privatekey : key;

        //set the key
        rsa.FromXmlString(keyToUse);

        //Determine the blocksizes for the iterations
        int blockSize = ((rsa.KeySize / 8) % 3 != 0) ? (((rsa.KeySize / 8) / 3) * 4) + 4 : ((rsa.KeySize / 8) / 3) * 4;

        int iterations = ciphertext.Length / blockSize;
        byte[] allPlaintextAsBytes = new byte[0];


        try
        {
            for (int i = 0; i < iterations; i++)
            {
                //to decrypt this we have to take the cipher text from a base 64 string an array.
                byte[] cipherTextAsBytes = Convert.FromBase64String(ciphertext.Substring(blockSize * i, blockSize));

                byte[] partialPlaintextAsBytes = rsa.Decrypt(cipherTextAsBytes, false);
            }
        }....(Catch Exceptions down here)

我知道这不是最好将文件分割到RSA的。是的,通常您将密钥加密到带有RSA的AES流密码,并使用AES加密文件。这是我正在做的一个项目,所以我一定要这样做。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

真实世界的RSA实现会填充,这会影响可以加密的明文的最大长度。

特别是,PKCS#1填充(最常见的类型)仅支持k - 11字节长的明文,其中k是密钥长度。 OAEP填充只接受高达k - 2 *哈希长度 - 2长的明文(OAEP允许您更改您正在使用的哈希算法)。

相关问题