473,408 Members | 2,832 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Padding is invalid and cannot be removed [Cryptography]

Hi there.

I'm coding an encryption / decryption program.
At this very moment, I think I should be pretty close from the end,
but there's something blocking me on my way.

There's a "Padding is invalid and cannot be removed" error raised when
closing the cryptostream (or FlushFinalBlock-ing it).
For what I have read, Padding errors are due to an incorrect padding :
PKCS7 is recommended.
But sadly, even using rijndaelAlg.Padding = Padding.PKCS7; , the error
is still raised.
Here's the code.
using System;
using System.Collections.Generic,
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace Project
{
class EncryptedData
{
// contains the names of the files where encrypted
data will be
stored
public string Enc_File
{
get {return enc_file};
set {enc_file = value};
}
string enc_file;
public string Enc_Key
{
get {return enc_key};
set {enc_key = value};
}
string enc_key;
public string Enc_IV
{
get {return enc_IV};
set {enc_IV = value};
}
string enc_IV;
}
class LetsDoIt
{
const int RSA_KEY_SIZE = 4096;
static void Main()
{
try
{
RSACryptoServiceProvider RSACrypto =
new
RSACryptoServiceProvider(RSA_KEY_SIZE);
EncryptedData encFiles = new
EncryptedData();
encFiles = encrypt("toEncrypt.txt",
RSACrypto.ExportParameters(false));
string decFile = decrypt(encFiles,
RSACrypto.ExportParameters(true));
}
catch (Exception e) { Console.WriteLine("Error
in Main: {0}",
e.Message); }
}
static EncryptedData encrypt(string FileToEncrypt,
RSAParameters
RSAParam)
{
try
{
// Part 1 : encrypting data
// 1 : create a Rijndael instance.
Rijndael rijndaelAlg =
Rijndael.Create();
rijndaelAlg.Mode = CipherMode.CBC;
/* rijndaelAlg.Padding = PaddingMode.PKCS7; */
rijndaelAlg.GenerateKey();
rijndaelAlg.GenerateIV();
ICryptoTransformer rijndaelEncryptor
=
rijndael.CreateEncryptor(rijndaelAlg.Key, rijndaelAlg.IV);
// 2 : open source and destination
files
FileStream fstf =
File.Open(FileToEncrypt, FileMode.OpenOrCreate);

EncryptedData encryptedFiles = new
EncryptedData();
encryptedFiles.Enc_File =
"encryptedFile";
FileStream fstef = new
FileSream(encryptedFiles.Enc_File,
FileMode.OpenOrCreate);
// 3 : Encrypting data
CryptoStream cstf = new
CryptoStream(fstef, rijndaelEncryptor,
CryptoStreamMode.Write);
byte[] bEncFile = new byte[(int)fstf.Length];
fstf.Read(bEncFile, 0, (int)bEncFile.Length);
cstf.Write(bEncFile, 0, (int)bEncFile.Length)
// 4 : closing streams
cstf.Close();
fstef.Close();
fstf.Close();
// Part 2 : encrypting keys
// 1 : create a RSA instance, and
import the public keys
RSACryptoServiceProvider RSA = new
RSACryptoServiceProvider(RSA_KEY_SIZE);
RSA.ImportParameters(RSAParam);
// 2 : encrypt Rijndael keys
byte[] EncKey_byte =
RSA.Encrypt(rijndaelAlg.Key, false);
byte[] EncIV_byte =
RSA.Encrypt(rijndaelAlg.IV, false);

encryptedFiles.Enc_Key = "Enc_Key";
encryptedFiles.Enc_IV = "Enc_IV";

ByteToFile(EncKey_byte, encryptedFiles.Enc_Key);
ByteToFile(EncIV_byte, encryptedFiles.Enc_IV);
return encryptedFiles;
}
catch (Exception e) { Console.WriteLine("Error
in encrypt: {0}",
e.Message); }
}
static string decrypt(EncryptedData encData,
RSAParameters RSAParam)
{
try
{
// 1 : get files' contents
byte[] EncKey_byte =
FileToByte(encData.Enc_Key);
byte[] EncIV_byte = FileToByte(encData.Enc_IV);
// 2 : decrypt keys with RSA
algorithm
RSACryptoServiceProvider RSA =
RSACryptoServiceProvider();
RSA.ImportParameters(RSAParam);
byte[] Key_byte =
RSA.Decrypt(EncKey_byte, false);
byte[] IV_byte =
RSA.Decrypt(EncIV_byte, false);
// 3 : decrypt the file using the
rijndael keys
Rijndael rijndaelAlg =
Rijndael.Create();
rijndaelAlg.Mode = CipherMode.CBC;
/* rijndaelAlg.Padding = PaddingMode.PKCS7; */
ICryptoTransform rijndaelDecryptor =
rijndaelAlg.CreateDecryptor(Key_byte, IV_byte);
FileStream fstef =
File.Open(encData.Enc_File, FileMode.Open);
string DecFile = "dec_file";
FileStream fstf = File.Open(DecFile, FileMode.OpenOrCreate);
CryptoStream cstef = new
CryptoStream(fstef, rijndaelDecryptor,
CryptoStreamMode.Write);
byte[] bDecFile = new byte[(int)fstef.Length];
fstef.Read(bDecFile, 0, (int)bDecFile.Length];
cstef.Write(bDecFile, 0, (int)bDecFile.Length]

// 4 : Closing Streams
cstef.Close(); // Here's where things are bad :(
fstef.Close();
fstf.Close();

return DecFile;
}
catch (Exception e) { Console.WriteLine("Error
in decrypt: {0}",
e.Message); }
}

static byte[] FileToByte(string FileName)
{
FileStream fst = new FileStream(FileName, FileMode.Open);
byte[] b_data = new byte[(int)fst.Length];
fst.Read(b_data, 0, (int)b_data.Length);
fst.Close();
return b_data;
}

static void ByteToFile(byte[] b_data, string FileName);
{
FileStream fst = new FileStream(FileName, FileMode.OpenOrCreate);
fst.Write(b_data, 0, (int)b_data.Length);
fst.Close();
}
}

Jul 19 '07 #1
3 5778
On Thu, 19 Jul 2007 03:22:34 -0700, floppyzedolfin
<fl************@gmail.comwrote:
// 3 : decrypt the file using the rijndael keys
Rijndael rijndaelAlg = Rijndael.Create();
rijndaelAlg.Mode = CipherMode.CBC;
/* rijndaelAlg.Padding = PaddingMode.PKCS7; */
Assuming you have correctly copied your code, you could try
uncommenting this line.
ICryptoTransform rijndaelDecryptor = rijndaelAlg.CreateDecryptor(Key_byte, IV_byte);
If that wasn't the problem, then try cutting down your code to a
*minimal* program that exhibits the same problem. Often this process
will show you where the problem is.

rossum

Jul 19 '07 #2
On 19 juil, 12:43, rossum <rossu...@coldmail.comwrote:
On Thu, 19 Jul 2007 03:22:34 -0700, floppyzedolfin

<floppyzedol...@gmail.comwrote:
// 3 : decrypt the file using the rijndael keys
Rijndael rijndaelAlg = Rijndael.Create();
rijndaelAlg.Mode = CipherMode.CBC;
/* rijndaelAlg.Padding = PaddingMode.PKCS7; */

Assuming you have correctly copied your code, you could try
uncommenting this line.

I've tried it before commenting it - and it was completely
unsuccessful. And it's the same for other padding modes (such as None,
Zeros, ANSIX923 or ISO10126)

There must be something I've got wrong, but I can't see what :(
Jul 20 '07 #3
On Fri, 20 Jul 2007 00:15:37 -0700, floppyzedolfin
<fl************@gmail.comwrote:
>On 19 juil, 12:43, rossum <rossu...@coldmail.comwrote:
>On Thu, 19 Jul 2007 03:22:34 -0700, floppyzedolfin

<floppyzedol...@gmail.comwrote:
// 3 : decrypt the file using the rijndael keys
Rijndael rijndaelAlg = Rijndael.Create();
rijndaelAlg.Mode = CipherMode.CBC;
/* rijndaelAlg.Padding = PaddingMode.PKCS7; */

Assuming you have correctly copied your code, you could try
uncommenting this line.


I've tried it before commenting it - and it was completely
unsuccessful. And it's the same for other padding modes (such as None,
Zeros, ANSIX923 or ISO10126)

There must be something I've got wrong, but I can't see what :(
There are lots of things wrong with it, it wouldn't even compile
correctly on my machine.
public string Enc_File
{
get {return enc_file};
Your }; should be ;}
set {enc_file = value};
Ditto.
public string Enc_Key
Same again.

public string Enc_IV
And again.

byte[] bEncFile = new byte[(int)fstf.Length];
Unmatched ]
cstf.Write(bEncFile, 0, (int)bEncFile.Length)
Missing ;
byte[] bDecFile = new byte[(int)fstef.Length];
Unmatched ]
fstef.Read(bDecFile, 0, (int)bDecFile.Length];
Same again.
cstef.Write(bDecFile, 0, (int)bDecFile.Length]
And again.
static void ByteToFile(byte[] b_data, string FileName);
Do you *really* want a semicolon at the end of that line?
{
FileStream fst = new FileStream(FileName, FileMode.OpenOrCreate);
fst.Write(b_data, 0, (int)b_data.Length);
fst.Close();
}
If you want us to help, then it is in your interest to post
*compilable* code. We should be able to cut and paste from your
posting into our compilers and get it to compile first time. Your
code fails this test. Compile your code and when it compiles OK cut
and paste it into your posting.

rossum
Jul 20 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Nicholas Holder | last post by:
A client creates a connection to the server using the TCPListener/Client classes and transfers data via a NetworkStream. When the client connects, the server creates a process and redirects its...
0
by: Robert Smith | last post by:
I am getting the following error being caught in my application_error method... I have no code referencing the crypto classes. I have found nothing on the net outside of people with crypto...
0
by: dba123 | last post by:
I am getting the following error when a sub domain is receiving a shared cookie: I have this in both web.config of each application. The 1.1 application does not have the decryption= value...
0
by: mjweiner | last post by:
I have an ajax.asp.net application that is running very well, however, my error log is continuing to fill with "padding is invalid and cannot be removed" These errors report that the url with the...
2
by: Brent K | last post by:
Ok, I have an internal intranet website created in visual studio 2005, c#. It was running fine for months, and then all of the sudden a few days I started getting these errors emailed to me (I have...
1
by: rdlauer | last post by:
For some time now we've been seeing seemingly random errors thrown by an application "Padding is invalid and cannot be removed". Everything I've read about this online suggests that the machine key...
0
by: Amelyan | last post by:
Why does this happen? How to fix it? Once in a while I get error in ~/ScriptResource.axd?d=... System.Reflection.TargetInvocationException: Exception has been thrown by the target of an...
2
by: Amelyan | last post by:
Why does this happen? How to fix it? Once in a while I get error in ~/ScriptResource.axd?d=... System.Reflection.TargetInvocationException: Exception has been thrown by the target of an...
9
by: AG | last post by:
I occassionally get the following exception from an ASP.NET 2.0 Web Application running on a shared web host. I have no way of knowing what the actual request page was as it never happens when I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.