|
Sorry - this is not more elegant. All you did to make it small was compact everything together and put multiple lines of code on the same line. I think other people have already mentioned that it was buggy below, so I won't go into that. I've been a developer for 20 years, and I can tell you that smaller isn't always better, especially when you're trying to teach something. And passing a bool to a function to fundamentally change what it's doing (encrypting versus decrypting) would get you laughed off the floor, it's such an amateur design mistake.
|
|
|
|
|
Dear Elmu,
There is nothing worse than a show off. No one is perfect and being new to encryption, I actually found the original code much more easy to understand and implement - with some modifications thanks to the comments.
Please be kind and keep your aggression in your pants man!
|
|
|
|
|
thats really works simple
thanks for all
with Best Regards
M.S. Babaei
-- modified at 5:37 Saturday 17th November, 2007
|
|
|
|
|
You may also be interested in looking at the following, related Code Project articles:
Generic SymmetricAlgorithm Helper[^]
This is a generic helper class that exposes simplified Encrypt and Decrypt functionality for strings, byte arrays and streams for any SymmetricAlgorithm derivative (DES, RC2, Rijndael, TripleDES, etc.).
Making TripleDES Simple in VB.NET and C#[^]
This is a simple wrapper class that provides an easy interface for encrypting and decrypting byte arrays and strings using the 3DES algorithm.
|
|
|
|
|
Hi,
I'm currently implementing an Application that makes heavy use of encrypting-/decrypting data. Luckily I have found this article at CodeProject.
Unfortunately I have to implement all this stuff using the Compact Framework 2.0 in a Windows Mobile-based project.
The sample code references a class PasswordDeriveBytes that is missing in CF (like so much other stuff!).
Does the CF contain a similar class, that I can use?
Best regards
Reiner
PS: I'm really NOT a specialist for Crypto-algs and the like...
|
|
|
|
|
Hi, I'm new to encryption. I have read in numerous places that Rijndael is *almost* synonymous with AES. I am writing a basic text-only chat system that I would like to implement a strong AES encryption on all data being transferred between client/server. I am wondering how secure this encryption method is, and if it is a form of AES, or it is just based on similar principals as AES.
I do not plan on sharing keys across the internet/intranet, only encrypted data will be transmitted. The key will be the same for all clients (possibly a list of keys to round-robin through). Also this software is only to be released to trusted parties, which will not have direct access to the keys themselves, so I am less worried about the encryption keys landing in the wrong hands. I am using 64 byte strings for the passwords being passed in.
I have been scouring the internet trying to find implementations of AES in C#, but I can't seem to find anything specific. If this won't work for me for AES, can anyone point me in the right direction to find some C# code that can teach me how to implement AES properly?
Thanks
|
|
|
|
|
I've just noticed that if you encrypt a text file, some of the file content is remove on decryption (clipped). (e.g. Encrypt file with following content "There is a problem with file encryption and decryption", you might only be able to decrypt "There is a problem with file encryption and "). This only applied to file not strings nor arrays. Can anyone figure out what is causing this/
Cheers.
-- modified at 18:55 Monday 5th March, 2007
|
|
|
|
|
after writing last byte to stream You should call cryptoStream.FlushFinalBlock();
Roman Czarko-Wasiutycz
|
|
|
|
|
I was testing this algorithm and I have had some problems.
First, I had the padding error. I tried no padding, and the size was not ok.
So I followed the other guy's suggestion and I used ISO padding.
However when I get to decrypt I'm getting a totally different string, and I don't know why.
Could it be the Conversion that is going bad?
These are what I used. Otherwise, it was exactly the same as your algorithm.
To turn a string into bytes:
byte[] byteData = Encoding.Unicode.GetBytes(Data);
To get the bytes back into a string:
byte[] encryptedData = ms.ToArray();
return System.Convert.ToBase64String(encryptedData);
Thanks
Andrew
|
|
|
|
|
hey I get that "Padding is invalid" when I try to send a byte array to a web service that catches the byte array. any ideas why ? I tried adding alg.Padding = PaddingMode.None;
didnt help.. here is my code
uploading code...
int numIterations = 0;
this.LocalFileName = Path.GetFileName(this.LocalFilePath);
if (this.AutoSetChunkSize)
this.ChunkSize = 16 * 1024;
if (!File.Exists(LocalFilePath))
throw new Exception(String.Format("Could not find file {0}", LocalFilePath));
long FileSize = new FileInfo(LocalFilePath).Length;
string FileSizeDescription = GetFileSize(FileSize); // e.g. "2.4 Gb" instead of 240000000000000 bytes etc...
long SentBytes = 0; // this variable is used to inform the user interface of the upload progress
byte[] Buffer = new byte[ChunkSize]; // this buffer stores each chunk, for sending to the web service via MTOM
using (FileStream fs = new FileStream(this.LocalFilePath, FileMode.Open, FileAccess.Read))
{
int BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the first chunk in the buffer
// send the chunks to the web service one by one, until FileStream.Read() returns 0, meaning the entire file has been read.
while (BytesRead > 0 && !this.CancellationPending)
{
try
{
//encrypts the byte array
Buffer = Rijindael.Encrypt(Buffer,"LMI");
etc...
and here is my code to get it back
...
// download the chunks from the web service one by one, until all the bytes have been read, meaning the entire file has been downloaded.
while (ReceivedBytes < FileSize && !this.CancellationPending)
{
if (this.AutoSetChunkSize && numIterations == AverageSample) // take an average of the first 5 transfers
{
long timeForInitialChunks = (long)DateTime.Now.Subtract(StartTime).TotalMilliseconds;
long averageChunkTime = Math.Max(1, timeForInitialChunks / AverageSample); // average of 5 chunks, in ms
this.ChunkSize = (int)Math.Min(4000000, this.ChunkSize * PreferredTransferDuration / averageChunkTime); // set the chunk size so that it takes 2 seconds per chunk (estimate), but not greater than 4mb
}
try
{
// although the DownloadChunk returns a byte[], it is actually sent using MTOM because of the configuration settings.
byte[] Buffer = Rijindael.Decrypt(this.WebService.DownloadChunk(this.RemoteFileName, ReceivedBytes, ChunkSize), "LMI");
...
let me know if you need more of my code. thanls
It's not a bug it's a fe- oh wait... no..It's a bug.
|
|
|
|
|
after fooling around and searching online I fixed it... it turns out I need to set the padding to ISO10126.
any places that have
Rijndael alg = Rjndael.Create();
(this appeared twice in my client program, and twice in the web service)
I added this code directly below and it worked!
alg.Padding = PaddingMode.ISO10126;
dont ask me why!
It's not a bug it's a f- oh wait... no..It's a bug.
|
|
|
|
|
Just what the doctor ordered. I'm doing ASP.NET file upload and want to encrypt/decrypt the files uploaded/downloaded.
Thanks for sharing.
Regards,
Simon Hughes
|
|
|
|
|
Very good and simple piece of code.
Thanks a lot
Regards,
Rodrigo C. Souza
|
|
|
|
|
Who is Ivan Medvedev?
!?
|
|
|
|
|
Was going to post that question as well. Regardless...using own salt...don't like the taste of the salt that was provided.
|
|
|
|
|
what if the user enters a wrong password for decryption?
it seems there is no validation and the program will malfunction..
do respond on this and let me knw i am wrong
|
|
|
|
|
Help me with my project.
I'm a student and i must to do a script which had to do digital signature on the web forms. For me it's realy hard. If exist anyone who can help me, i will be recongnizant. Contact me please: sergiunas@yahoo.com
Thank you in advance!
Sergiu
|
|
|
|
|
I'm using escentually this algorithm. However every time I accept an MS security update I seem to loose the ability to decrypt anything that I have encrypted.
It there some connection between this code and the security updates?
|
|
|
|
|
I'm new to encryption, but I took out the comments from your file Encrypt() and file Decrtypt() functions, and they are completely identical. Does encrypting an encrypted file just decrypt it?
|
|
|
|
|
I have been reading this article and found that if i input a password that needs to be encrpted of example 10 characters, it returns only the first 8 characters in a string when decrypting.
I'm using the following code to decrypt
<br />
<br />
public static string Encrypt(string clearText)<br />
{<br />
string Password = PASSWORD;<br />
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);<br />
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,<br />
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });<br />
<br />
MemoryStream ms = new MemoryStream();<br />
<br />
Rijndael alg = Rijndael.Create();<br />
<br />
alg.Key = pdb.GetBytes(32);<br />
alg.IV = pdb.GetBytes(16);<br />
<br />
CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);<br />
<br />
cs.Write(clearBytes, 0, clearBytes.Length);<br />
<br />
cs.Close();<br />
<br />
byte[] encryptedData = ms.ToArray();<br />
<br />
return Convert.ToBase64String(encryptedData);<br />
}<br />
<br />
public static string Decrypt(string cipherText)<br />
{<br />
string Password = PASSWORD;<br />
byte[] cipherBytes = Convert.FromBase64String(cipherText);<br />
<br />
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,<br />
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });<br />
<br />
MemoryStream ms = new MemoryStream();<br />
<br />
Rijndael alg = Rijndael.Create();<br />
alg.Key = pdb.GetBytes(32);<br />
alg.IV = pdb.GetBytes(16);<br />
<br />
CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);<br />
<br />
cs.Write(cipherBytes, 0, cipherBytes.Length);<br />
byte[] decryptedData = ms.ToArray();<br />
<br />
return System.Text.Encoding.Unicode.GetString(decryptedData);<br />
}<br />
<br />
where PASSWORD is dclared with the class.
Where should i look for changing the lenght of the returned string.
I have tried making the PASSWORD longer as i thought that would help when i read this part:
=========== QUOTE =============
If you are using just small letters that gives you about 5 bits of information per character and your password will have to be over 25 characters long to get to 128bit. If you are using capital letters and some symbols you can get to about 7 bits per character and your password minimum length to around 18 characters (how long is your password? ).
===============================
-- modified at 2:20 Wednesday 31st August, 2005
|
|
|
|
|
Hello!
I tried to use RSACryptographicServiceProvider to encrypt/decrypt some data passed to WebService in different location, by creating a private key for decryption and public key for encryption on server side. I used an xml document to send the public key information to client.
The process of encryption works fine in both XP and Win2000 systems, but fails to decrypt in Win2000 system.
The problem is in function
RSACryptographicServiceProvider.Decrypt(byte []EncryptedData, bool OAEPP)
In MSDN reference written that the function must use false value for the second parameter in Windows 2000 system as it doesn't support the special panding characteristics. Navertheless, it also failed in win2000 system with a false value. I know that to data to string I have to use Convert.ToBase64String function. I will thank to everyone who knows this problem.
Eli
|
|
|
|
|
What was the error you received? I am also having issues decrypting, somehow the data is too large for the modulus of 128. Any solution?
|
|
|
|
|
The error was "The RSACryptoServiceProvider for this implementation could not be acquired". I"ve already solved this: the problem was that MachineKey storage folder (hidden folder) must have access permissions for users.
|
|
|
|
|
Thanks for the info.
If you included a sample code on how the functions are called, it helps more.
Abdu
|
|
|
|
|
********************************************************
SIMPLE ENCRYPTION CODE USING JAVA WITH REALJ
********************************************************
MAIN CLASS: Encryption.java
public class Encryption
{
public static void main (String[] args)
{
Encryptor code = new Encryptor("Insert Password HER!!");
code.code("Simple Encryption Code");
System.out.println(code);
Decryptor decode = new Decryptor(code.crypterStr);
decode.decode(code.toString());
System.out.println(decode);
}
}
----------------------------------------------------------------------
Encryptor.java
import java.util.Random;
public class Encryptor
{
Random num = new Random();
String[] card = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "a", "b", "c", "d", "e",
"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z", ".", ",", "!", "$", "%",";", ":", "?", "(", ")", "@",
"[", "]", "{", "}", "~", "#", "&", "^", "/", "*", "_", "-", "=", "+", "\"", "|",
"/", "\'", "\\"};
private String[] message, coded, keyString;
public String[][] crypterStr;
private int p = 100;// number of shuffles
private int[] mixed, key;
private int[][] crypter;
public Encryptor(String keyStr)
{
keyString = new String[keyStr.length()];
key = new int[keyString.length];
crypter = new int[keyString.length][15];
crypterStr = new String[crypter.length][crypter[0].length];
for(int keyCount=0; keyCount<keyString.length; keyCount++)
keyString[keyCount] = keyStr.charAt(keyCount)+"";
for(int turn=0; turn<keyString.length; turn++)
{
for(int search=0; search<card.length; search++)
if(keyString[turn].compareTo(card[search])==0)
key[turn] = search;
}
for(int i=0; i<crypter.length; i++)
{
crypter[i][0] = key[i];
for(int j=1; j<crypter[i].length; j++)
{
int mixer = num.nextInt(key.length);
crypter[i][j] = key[mixer];
}
}
for(int shuff=0; shuff<p; shuff++)
for(int i=0; i<crypter.length; i++)
for(int j=0; j<crypter[i].length; j++)
key[i] ^= crypter[i][j];
for(int i=0; i<crypter.length; i++)
for(int j=0; j<crypter[i].length; j++)
crypterStr[i][j] = card[crypter[i][j]];
}
public void code(String a)
{
message = new String[a.length()];
mixed = new int[a.length()];
for(int care=0; care<message.length; care++)
message[care] = a.charAt(care)+"";
for(int turn=0; turn<mixed.length; turn++)
{
for(int search=0; search<card.length; search++)
if(message[turn].compareTo(card[search])==0)
mixed[turn] = search;
}
for(int mix=0; mix<mixed.length; mix++)
mixed[mix] ^= key[mix];
coded = new String[mixed.length];
for(int mix2=0; mix2<mixed.length; mix2++)
coded[mix2] = card[mixed[mix2]]+"";
}
public String toString()
{
String mess="";
for(int m=0; m<message.length; m++)
mess += coded[m]+"";
return mess;
}
}
----------------------------------------------------------------------
Decryptor.java
public class Decryptor
{
String[] card = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "a", "b", "c", "d", "e",
"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z", ".", ",", "!", "$", "%",";", ":", "?", "(", ")", "@",
"[", "]", "{", "}", "~", "#", "&", "^", "/", "*", "_", "-", "=", "+", "\"", "|",
"/", "\'", "\\"};
private String[] message, coded, keyString;
private int p = 100;// number of shuffles
private int[] mixed, key;
private int[][] decrypter;
public Decryptor(String[][] a)
{
decrypter = new int[a.length][a[0].length];
keyString = new String[a.length];
key = new int[a.length];
for(int i=0; i<a.length; i++)
{
keyString[i] = a[i][0];
for(int j=0; j<a[i].length; j++)
{
for(int search=0; search<card.length; search++)
if(a[i][j].compareTo(card[search])==0)
decrypter[i][j] = search;
}
}
for(int turn=0; turn<keyString.length; turn++)
{
for(int search=0; search<card.length; search++)
if(keyString[turn].compareTo(card[search])==0)
key[turn] = search;
}
for(int shuff=0; shuff<p; shuff++)
for(int i=0; i<decrypter.length; i++)
for(int j=0; j<decrypter[i].length; j++)
key[i] ^= decrypter[i][j];
}
public void decode(String a)
{
message = new String[a.length()];
mixed = new int[a.length()];
for(int care=0; care<message.length; care++)
message[care] = a.charAt(care)+"";
for(int turn=0; turn<mixed.length; turn++)
{
for(int search=0; search<card.length; search++)
if(message[turn].compareTo(card[search])==0)
mixed[turn] = search;
}
for(int mix=0; mix<mixed.length; mix++)
mixed[mix] ^= key[mix];
coded = new String[mixed.length];
for(int mix2=0; mix2<mixed.length; mix2++)
coded[mix2] = card[mixed[mix2]]+"";
}
public String toString()
{
String mess="";
for(int m=0; m<message.length; m++)
mess += coded[m]+"";
return mess;
}
}
|
|
|
|
|