问题是我已经使用我想出的以下代码使用 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)));
}
问题是当我尝试解密时,我必须将我放入 base 64 的密文转换为 base 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 IT。是的,通常您使用 RSA 将密钥加密为流密码(如 AES)并使用 AES 加密文件。这是我正在做的一个项目,所以我必须这样做。
提前感谢您的帮助。