問題は、私が思いついたこのコードを使用して、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 でファイルを暗号化します。これは私が行っているプロジェクトなので、この方法で行う必要があります。
事前に助けてくれてありがとう。