///
/// Encrypt file
///
/// Path to file need to be encrypted
/// Path to file after being encrypted
/// Path to Public key file
public void EncryptFile(string inputFile, string outputFile, string strPubKey)
{
try
{
bool IsFileExist = File.Exists(inputFile);
if (!IsFileExist)
{
throw new FileNotFoundException();
}
//FileStream to create and Read file
FileStream fsPubkey = new FileStream(strPubKey, FileMode.Open, FileAccess.Read);
FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
RSACryptoServiceProvider myRSA = new RSACryptoServiceProvider();
//Read public key file
byte[] bytePubkey = new byte[fsPubkey.Length];
fsPubkey.Read(bytePubkey, 0, bytePubkey.Length);
myRSA.FromXmlString(ASCIIEncoding.ASCII.GetString(bytePubkey, 0, bytePubkey.Length));
byte[] byteInput = new byte[fsInput.Length];
fsInput.Read(byteInput, 0, byteInput.Length);
byte[] byteEnc;
byteEnc = myRSA.Encrypt(byteInput, false);
//write encrypted data to outputFile
fsOutput.Write(byteEnc, 0, byteEnc.Length);
fsInput.Flush();
fsPubkey.Flush();
fsOutput.Flush();
fsInput.Close();
fsPubkey.Close();
fsOutput.Close();
}
catch (CryptographicException exc)
{
throw exc;
}
catch (Exception exc)
{
throw exc;
}
}
Can everybody help me fix it ?
Replies
Know the answer? Post it — somebody with the same question will find it here.