473,795 Members | 3,215 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Pad ding = Padding.PKCS7; , the error
is still raised.
Here's the code.
using System;
using System.Collecti ons.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
{
RSACryptoServic eProvider RSACrypto =
new
RSACryptoServic eProvider(RSA_K EY_SIZE);
EncryptedData encFiles = new
EncryptedData() ;
encFiles = encrypt("toEncr ypt.txt",
RSACrypto.Expor tParameters(fal se));
string decFile = decrypt(encFile s,
RSACrypto.Expor tParameters(tru e));
}
catch (Exception e) { Console.WriteLi ne("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.Mod e = CipherMode.CBC;
/* rijndaelAlg.Pad ding = PaddingMode.PKC S7; */
rijndaelAlg.Gen erateKey();
rijndaelAlg.Gen erateIV();
ICryptoTransfor mer rijndaelEncrypt or
=
rijndael.Create Encryptor(rijnd aelAlg.Key, rijndaelAlg.IV) ;
// 2 : open source and destination
files
FileStream fstf =
File.Open(FileT oEncrypt, FileMode.OpenOr Create);

EncryptedData encryptedFiles = new
EncryptedData() ;
encryptedFiles. Enc_File =
"encryptedFile" ;
FileStream fstef = new
FileSream(encry ptedFiles.Enc_F ile,
FileMode.OpenOr Create);
// 3 : Encrypting data
CryptoStream cstf = new
CryptoStream(fs tef, rijndaelEncrypt or,
CryptoStreamMod e.Write);
byte[] bEncFile = new byte[(int)fstf.Lengt h];
fstf.Read(bEncF ile, 0, (int)bEncFile.L ength);
cstf.Write(bEnc File, 0, (int)bEncFile.L ength)
// 4 : closing streams
cstf.Close();
fstef.Close();
fstf.Close();
// Part 2 : encrypting keys
// 1 : create a RSA instance, and
import the public keys
RSACryptoServic eProvider RSA = new
RSACryptoServic eProvider(RSA_K EY_SIZE);
RSA.ImportParam eters(RSAParam) ;
// 2 : encrypt Rijndael keys
byte[] EncKey_byte =
RSA.Encrypt(rij ndaelAlg.Key, false);
byte[] EncIV_byte =
RSA.Encrypt(rij ndaelAlg.IV, false);

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

ByteToFile(EncK ey_byte, encryptedFiles. Enc_Key);
ByteToFile(EncI V_byte, encryptedFiles. Enc_IV);
return encryptedFiles;
}
catch (Exception e) { Console.WriteLi ne("Error
in encrypt: {0}",
e.Message); }
}
static string decrypt(Encrypt edData encData,
RSAParameters RSAParam)
{
try
{
// 1 : get files' contents
byte[] EncKey_byte =
FileToByte(encD ata.Enc_Key);
byte[] EncIV_byte = FileToByte(encD ata.Enc_IV);
// 2 : decrypt keys with RSA
algorithm
RSACryptoServic eProvider RSA =
RSACryptoServic eProvider();
RSA.ImportParam eters(RSAParam) ;
byte[] Key_byte =
RSA.Decrypt(Enc Key_byte, false);
byte[] IV_byte =
RSA.Decrypt(Enc IV_byte, false);
// 3 : decrypt the file using the
rijndael keys
Rijndael rijndaelAlg =
Rijndael.Create ();
rijndaelAlg.Mod e = CipherMode.CBC;
/* rijndaelAlg.Pad ding = PaddingMode.PKC S7; */
ICryptoTransfor m rijndaelDecrypt or =
rijndaelAlg.Cre ateDecryptor(Ke y_byte, IV_byte);
FileStream fstef =
File.Open(encDa ta.Enc_File, FileMode.Open);
string DecFile = "dec_file";
FileStream fstf = File.Open(DecFi le, FileMode.OpenOr Create);
CryptoStream cstef = new
CryptoStream(fs tef, rijndaelDecrypt or,
CryptoStreamMod e.Write);
byte[] bDecFile = new byte[(int)fstef.Leng th];
fstef.Read(bDec File, 0, (int)bDecFile.L ength];
cstef.Write(bDe cFile, 0, (int)bDecFile.L ength]

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

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

static byte[] FileToByte(stri ng FileName)
{
FileStream fst = new FileStream(File Name, FileMode.Open);
byte[] b_data = new byte[(int)fst.Length];
fst.Read(b_data , 0, (int)b_data.Len gth);
fst.Close();
return b_data;
}

static void ByteToFile(byte[] b_data, string FileName);
{
FileStream fst = new FileStream(File Name, FileMode.OpenOr Create);
fst.Write(b_dat a, 0, (int)b_data.Len gth);
fst.Close();
}
}

Jul 19 '07 #1
3 5834
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.Mod e = CipherMode.CBC;
/* rijndaelAlg.Pad ding = PaddingMode.PKC S7; */
Assuming you have correctly copied your code, you could try
uncommenting this line.
ICryptoTransfor m rijndaelDecrypt or = rijndaelAlg.Cre ateDecryptor(Ke y_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...@coldm ail.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.Mod e = CipherMode.CBC;
/* rijndaelAlg.Pad ding = PaddingMode.PKC S7; */

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...@coldm ail.comwrote:
>On Thu, 19 Jul 2007 03:22:34 -0700, floppyzedolfin

<floppyzedol.. .@gmail.comwrot e:
// 3 : decrypt the file using the rijndael keys
Rijndael rijndaelAlg = Rijndael.Create ();
rijndaelAlg.Mod e = CipherMode.CBC;
/* rijndaelAlg.Pad ding = PaddingMode.PKC S7; */

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.Lengt h];
Unmatched ]
cstf.Write(bEnc File, 0, (int)bEncFile.L ength)
Missing ;
byte[] bDecFile = new byte[(int)fstef.Leng th];
Unmatched ]
fstef.Read(bDec File, 0, (int)bDecFile.L ength];
Same again.
cstef.Write(bDe cFile, 0, (int)bDecFile.L ength]
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(File Name, FileMode.OpenOr Create);
fst.Write(b_dat a, 0, (int)b_data.Len gth);
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
6613
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 StandardOut to traverse back over the network to the client. I want to encrypt this data and the code I have is below. However, occasionally during processing, I receive an exception stating the PKCS7 padding is invalid and cannot be removed. I have...
0
1486
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 issues. Please Help. ~rob Padding is invalid and cannot be removed. at
0
676
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 because you cannot have that for 1.1 or asp.net will error out. The source application is coded in .NET 2.0 but the target application that's sharing the source app's cookie is a .NET 1.1 app. <machineKey...
0
1304
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 error is http://www.mysitename.com/ScriptResource.axd?d= Here is a sample of what is returned: Error Message: Padding is invalid and cannot be removed. error Source: mscorlib targetSite: DecryptData Stack Trace:
2
6165
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 it set up to email me exceptions). Here is the error. I have gotten this error probably 100 times in the last 2 days. I have googled this error to no avail. My program is not doing any decrypting, I am not on a web farm, I have reset the web...
1
8592
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 is different between two load-balanced servers, but this application is running on just one server. The other odd thing is that the errors come in groups. Over a short period of time (5 minutes or so) many different users will hit this error...
0
3385
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 invocation. ---> System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. at
2
2196
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 invocation. ---> System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. at
9
2540
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 visit the site. The exception is trapped in the Application_Error event of global.asax and emailed to me. The only encryption in the app is the connectionStrings section of web.config.
0
9672
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10215
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7541
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.