0
Answer

Encrypt/decrypt file by using RSACryptoServiceProvider in C#

Ask a question
Man Vuong

Man Vuong

16y
3.9k
1
I've got some troubles when encrypting file by RSA. I could only encrypt text file or string, but always have bugs when encrypt other file types. Following is my code:

       /// <summary>
        /// Encrypt file
        /// </summary>
        /// <param name="inputFile">Path to file need to be encrypted</param>
        /// <param name="outputFile">Path to file after being encrypted</param>
        /// <param name="strPubKey">Path to Public key file</param>
        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 ?