|
I have this code for encryption-decryption some data, when i run it, it makes the exception: "Padding is invalid and cannot be removed"
I did everything i found in google or forums but none helped me.
I appreciate any ideas! Please help me!
This is the Code:
using System;<br />
using System.IO;<br />
using System.Text;<br />
using System.Security.Cryptography;<br />
<br />
<br />
public sealed class Cryption<br />
{<br />
private RijndaelManaged Algorithm;<br />
private MemoryStream memStream;<br />
private ICryptoTransform EncryptorDecryptor;<br />
private CryptoStream crStream;<br />
private StreamWriter strWriter;<br />
private StreamReader strReader;<br />
<br />
private string m_key;<br />
private string m_iv;<br />
<br />
private byte[] key;<br />
private byte[] iv;<br />
<br />
private string pwd_str;<br />
private byte[] pwd_byte;<br />
<br />
public Cryption(string key_val, string iv_val)<br />
{<br />
key = new byte[32];<br />
iv = new byte[32];<br />
<br />
int i;<br />
m_key = key_val;<br />
m_iv = iv_val;<br />
<br />
for(i=0;i<m_key.length;i++)><br />
{<br />
key[i] = Convert.ToByte(m_key[i]);<br />
}<br />
for(i=0;i<m_iv.length;i++)><br />
{<br />
iv[i] = Convert.ToByte(m_iv[i]);<br />
}<br />
<br />
}<br />
<br />
<br />
public string Encrypt(string s)<br />
{<br />
Algorithm = new RijndaelManaged();<br />
<br />
Algorithm.BlockSize = 256;<br />
Algorithm.KeySize = 256;<br />
Algorithm.Padding = PaddingMode.PKCS7;<br />
<br />
memStream = new MemoryStream();<br />
<br />
EncryptorDecryptor = Algorithm.CreateEncryptor(key,iv);<br />
<br />
crStream = new CryptoStream(memStream, EncryptorDecryptor, CryptoStreamMode.Write);<br />
<br />
strWriter = new StreamWriter(crStream);<br />
<br />
strWriter.Write(s);<br />
<br />
strWriter.Flush();<br />
crStream.FlushFinalBlock();<br />
<br />
pwd_byte = new byte[memStream.Length];<br />
memStream.Position = 0;<br />
memStream.Read(pwd_byte,0,(int)pwd_byte.Length);<br />
<br />
pwd_str= new UnicodeEncoding().GetString(pwd_byte); <br />
return pwd_str;<br />
}<br />
<br />
<br />
public string Decrypt(string s)<br />
{<br />
Algorithm = new RijndaelManaged();<br />
<br />
Algorithm.BlockSize = 256;<br />
Algorithm.KeySize = 256;<br />
<br />
MemoryStream memStream = new MemoryStream(new UnicodeEncoding().GetBytes(s));<br />
<br />
ICryptoTransform EncryptorDecryptor = Algorithm.CreateDecryptor(key,iv);<br />
memStream.Position = 0;<br />
CryptoStream crStream = new CryptoStream(memStream, EncryptorDecryptor, CryptoStreamMode.Read);<br />
strReader = new StreamReader(crStream);<br />
<br />
return strReader.ReadToEnd();<br />
}<br />
<br />
}<br />
|
|
|
|
|
Post the exception type and full stack trace. Also post any other details on the exception and any inner exceptions.
Simon
|
|
|
|
|
here is the stack trace:
System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed.<br />
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)<br />
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)<br />
at System.Security.Cryptography.CryptoStream.Read(Byte[] buffer, Int32 offset, Int32 count)<br />
at System.IO.StreamReader.ReadBuffer()<br />
at System.IO.StreamReader.ReadToEnd()<br />
at Cryptography.Cryption.Decrypt(String s) in F:\Comp\Crypt\Cryption.cs:line 96<br />
at CryptSample.Form1.btnDecrypt_Click(Object sender, EventArgs e) in F:\Comp\Crypt\Form1.cs:line 230<br />
I think it's somehow about the streamreader/writer (Am I right?) but i don't know how to fix it!!!
anyway THANK YOU for your attention.
Roshanak
|
|
|
|
|
The 3 most likely reasons for this error:
1) You are using different padding schemes when encrypting and decrypting.
2) You are using different encoding formats for encrypting and decrypting.
3) When encrypting you haven't properly flushed the stream out to the file.
Looking at your code it looks like you set the padding to pkcs7 when encrypting , but don't do the same when decrypting.
Simon
|
|
|
|
|
I set the padding to pkcs7 in both encryption and decryption and i build the project again but it still makes the exception.
About encoding format, i'm using unicodeEncoding in both,
you can see in encryption:
pwd_str= new UnicodeEncoding().GetString(pwd_byte);<br />
return pwd_str;
and in decryption:
MemoryStream memStream = new MemoryStream(new UnicodeEncoding().GetBytes(s));
and for the streams:
<br />
strWriter.Flush();<br />
crStream.FlushFinalBlock();
i don't know how else i can flush them!!!
Again THANKS
Roshanak
|
|
|
|
|
I think the problem is the way you are reading data out of the memory stream. Use a stream reader instead of getting the bytes and doing unicode encoding. I suspect that is screwing things up. Then use a stream writer to put the string back into the memory stream when decrypting. (This works fine on my PC if I make that change)
Roshanakak wrote: i don't know how else i can flush them!!!
You're not calling dispose no any of your streams. You should be using 'using' to properly dispose of the streams. Anything that has a dispose method should be created within a using block (or if not, make sure you call Dispose() in some other way - like in a finally block) Like this:
using (MemoryStream memStream = new MemoryStream())
{
using (ICryptoTransform EncryptorDecryptor = Algorithm.CreateEncryptor(key, iv))
{
using (CryptoStream crStream = new CryptoStream(memStream, EncryptorDecryptor, CryptoStreamMode.Write))
{
using (StreamWriter strWriter = new StreamWriter(crStream))
{
strWriter.Write(s);
strWriter.Flush();
crStream.FlushFinalBlock();
}
}
}
}
Also, you're using a bunch of member variables on the class that your just overwriting when you decrypt. Get rid of these and make them local variables in the method. That will prevent any crossover or leak of setup from one method to the other.
Simon
|
|
|
|
|
How to take gridview in c#?
|
|
|
|
|
U can do by this way.
******Design******
<asp:gridview id="GVCP" bordercolor="2" runat="server" width="90%" height="50px" xmlns:asp="#unknown">
AutoGenerateColumns="false" AllowPaging="True" >
<selectedrowstyle font-size="Medium" font-names="Arial" horizontalalign="Right" forecolor="White">
BackColor="#374E8C">
<alternatingrowstyle font-size="10px" font-names="Arial" forecolor="#333333" backcolor="#E4E6E9">
Wrap="False">
<rowstyle font-size="10px" font-names="Arial" forecolor="#333333" horizontalalign="Left">
Wrap="False">
<headerstyle cssclass="gridHead" wrap="False">
<columns> <asp:templatefield headertext="S.No.">
<itemtemplate>
<asp:label id="lblslno" text="<%#Container.DataItemIndex+1%>" runat="server" visible="True">
<itemstyle horizontalalign="Center">
<asp:boundfield datafield="PRICE" headertext="PRICE">
<itemstyle height="20px" horizontalalign="Center" width="20%">
<pagerstyle font-size="12px" font-names="Arial" horizontalalign="Right" forecolor="White">
BackColor="#374E8C">
******************** Code*****************
DataTable dt = objclsDB.GetDataTable("Select PRICE from tblemp")
GVCP.DataSource = dtCP;
GVCP.DataBind();
|
|
|
|
|
that depends on where you want to take it, although if I were you I'd be more concerned with figuring out "how to post intelligent question in forum?"
|
|
|
|
|
i am using C# Windows Application
at default i have stored some values in listbox
at page load i want to get all values from listbox
|
|
|
|
|
Where u binding these values in listbox ?? If u binding these in page_load then u can do it after binding some values in listbox.
try like this..
http://www.java2s.com/Code/CSharp/GUI-Windows-Form/Getselectedcheckboxlistitems.htm
|
|
|
|
|
I know that there is A C++ library for interoperability between C++ and Tcl.
I want to know how to do the similar thing for c#?
thanks.
|
|
|
|
|
I don't know the answer to this question but you can use DLLImport to use the method's from c++ as an exmaple I've done the following in the past
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
int nLeftRect,
int nTopRect,
int nRightRect,
int nBottomRect,
int nWidthEllipse,
int nHeightEllipse
);
hope that helps a bit
|
|
|
|
|
Hi
i've configured my typed dataSet for Insert/Update/Delete/Select with stored procedures.
my insert procedure returns pk of inserted record as output parameter. i use TableAdapter.Update method to insert/update/delete operations. my question is that how to get pk of inserted row when i use TableAdapter.Update ?
Note : i need pk of inserted record for update it's child table(s).
|
|
|
|
|
are you not using the PK field to identify which row it is you are updating?
Life goes very fast. Tomorrow, today is already yesterday.
|
|
|
|
|
i want to get Pk of inserted row
|
|
|
|
|
Hi,,
i added a new form window using "Add new Item" option. the new added form display in the solution explorer. BUT it object is not available into another form why?
I am calling this form from Form1.
using this code
Form4 frm4 = new Form4(); // error line
frm4.Show();
it give an error "The Namespace Form4 could not found"
??? Why this gives the error?
|
|
|
|
|
Have you checked they are in the same namespace? I'm assuming that the new form is called form 4
|
|
|
|
|
i have data set linked with table adapter(which is already linked with table in the database)
and i have datgrid linked with the dataset and when i add values to the table in the db, the added values does not add to the dataset and so does not add to the data grid.
WHY?
|
|
|
|
|
I think the values which u r adding to the table in DB those are not reflecting in that table. Try like this, After adding values to the table
dt.AcceptChanges(); // dt means DataTable
|
|
|
|
|
how can i change the step length for y-axis through using
rad chart because the values of y-axis is too large?
and
how to remove y-axes values from the chart?
|
|
|
|
|
Go to the company that produced it and ask on their forums. This forum is for general C# questions - nothing specific to any third party tool/components you may have purchased.
|
|
|
|
|
How to read the large data(containig 2000 records) from binary file please anyone help me with code.
|
|
|
|
|
You are first going to have to find out the format of the binary file. We don't know this so can't really help beyond the basics of how to open a file for reading.
|
|
|
|
|