Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8760491
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T15:03:27+00:00 2026-06-13T15:03:27+00:00

I am having some trouble getting a asp.net C# file encryption / decryption process

  • 0

I am having some trouble getting a asp.net C# file encryption / decryption process to work. I can get the file uploaded and ecrypted, but cannot get the decryption to work.

I get the error: Exception Details: System.Security.Cryptography.CryptographicException: Bad Data. on the decryption line:

byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

Here is my encrypt function:

   private void EncryptFile(string inFile)
    {
        RijndaelManaged rjndl = new RijndaelManaged();
        rjndl.KeySize = 256;
        rjndl.BlockSize = 256;
        rjndl.Mode = CipherMode.CBC;
        ICryptoTransform transform = rjndl.CreateEncryptor();

        byte[] keyEncrypted = rsa.Encrypt(rjndl.Key, false);

        byte[] LenK = new byte[4];
        byte[] LenIV = new byte[4];

        int lKey = keyEncrypted.Length;
        LenK = BitConverter.GetBytes(lKey);
        int lIV = rjndl.IV.Length;
        LenIV = BitConverter.GetBytes(lIV);

        int startFileName = inFile.LastIndexOf("\\") + 1;
        // Change the file's extension to ".enc"
        string outFile = EncrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc";

        lblDecryptFileName.Text = outFile;

        using (FileStream outFs = new FileStream(outFile, FileMode.Create))
        {
            outFs.Write(LenK, 0, 4);
            outFs.Write(LenIV, 0, 4);
            outFs.Write(keyEncrypted, 0, lKey);
            outFs.Write(rjndl.IV, 0, lIV);

            using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
            {
                int count = 0;
                int offset = 0;
                int blockSizeBytes = rjndl.BlockSize / 8;
                byte[] data = new byte[blockSizeBytes];
                int bytesRead = 0;
                using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                {
                    do
                    {
                        count = inFs.Read(data, 0, blockSizeBytes);
                        offset += count;
                        outStreamEncrypted.Write(data, 0, count);
                        bytesRead += blockSizeBytes;
                    }
                    while (count > 0);
                    inFs.Close();
                }
                outStreamEncrypted.FlushFinalBlock();
                outStreamEncrypted.Close();
            }
            outFs.Close();
        }

    }

And here is the decrypt function where the error occurs.

   private void DecryptFile(string inFile)
    {

        // Create instance of Rijndael for
        // symetric decryption of the data.
        RijndaelManaged rjndl = new RijndaelManaged();
        rjndl.KeySize = 256;
        rjndl.BlockSize = 256;
        rjndl.Mode = CipherMode.CBC;
        byte[] LenK = new byte[4];
        byte[] LenIV = new byte[4];
        string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";

        using (FileStream inFs = new FileStream(EncrFolder + inFile, FileMode.Open))
        {

            inFs.Seek(0, SeekOrigin.Begin);
            inFs.Seek(0, SeekOrigin.Begin);
            inFs.Read(LenK, 0, 3);
            inFs.Seek(4, SeekOrigin.Begin);
            inFs.Read(LenIV, 0, 3);

            int lenK = BitConverter.ToInt32(LenK, 0);
            int lenIV = BitConverter.ToInt32(LenIV, 0);
            int startC = lenK + lenIV + 8;
            int lenC = (int)inFs.Length - startC;

            // Create the byte arrays for
            // the encrypted Rijndael key,
            // the IV, and the cipher text.
            byte[] KeyEncrypted = new byte[lenK];
            byte[] IV = new byte[lenIV];

            // Extract the key and IV
            // starting from index 8
            // after the length values.
            inFs.Seek(8, SeekOrigin.Begin);
            inFs.Read(KeyEncrypted, 0, lenK);
            inFs.Seek(8 + lenK, SeekOrigin.Begin);
            inFs.Read(IV, 0, lenIV);
            Directory.CreateDirectory(DecrFolder);

            byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

            ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV);

            using (FileStream outFs = new FileStream(outFile, FileMode.Create))
            {

                int count = 0;
                int offset = 0;

                int blockSizeBytes = rjndl.BlockSize / 8;
                byte[] data = new byte[blockSizeBytes];

                inFs.Seek(startC, SeekOrigin.Begin);
                using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                {
                    do
                    {
                        count = inFs.Read(data, 0, blockSizeBytes);
                        offset += count;
                        outStreamDecrypted.Write(data, 0, count);

                    }
                    while (count > 0);

                    outStreamDecrypted.FlushFinalBlock();
                    outStreamDecrypted.Close();
                }
                outFs.Close();
            }
            inFs.Close();
        }

    }

Any help on this would be great! I am not an RSA encryption expert and have been reading a lot of posts but still not able to come up with a solution.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T15:03:28+00:00Added an answer on June 13, 2026 at 3:03 pm

    I have finally figured this out. The code worked well in a desktop application when I tried it there. It just didn’t work in the asp.net 4 web application I was trying to write. The issue was the RSA object wasn’t persisted through the session. So, the RSA object was created okay. The file was encrypted okay. But when I went to decrypt the file the RSA object was not there. The error message of System.Security.Cryptography.CryptographicException: Bad Data is misleading as that wasn’t really the issue, the data was fine.

    So, when creating the key and the RSA object I used the following:

    rsa = new RSACryptoServiceProvider(cspp);
    Session["rsa"] = rsa;
    

    Next, when the decryption function is called I added in:

    if (rsa == null)
         rsa = (RSACryptoServiceProvider)Session["rsa"];
    

    Of course, there is a little more code around this also so catch if there is no key for the RSA session, but this is the high level solution for the issue I was having.

    If anyone is looking for this let me know and I can share more of the code.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having some trouble getting log4net to work from ASP.NET 3.5. This is the
I've been having some trouble getting autocomplete to work specifically with a json file
I'm having some trouble getting binding to work with JQuery. <iframe id=wufooFormz7x3k1 height=281 allowtransparency=true
I am having some trouble getting Elmah to work with url routing in an
I'm having some trouble getting a static property through reflection in .NET 4.0. Say
I'm having some trouble getting debug mode to work on my android phone. I
I'm having some trouble getting a jQuery plugin to work correctly in my MVC
I am having some trouble when I use ASP .Net 4's URL Routing feature
I'm having some trouble getting my cache to work the way I want. The
I've been having trouble getting my ASP.NET application to automatically log users into the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.