473,320 Members | 2,054 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,320 software developers and data experts.

Encrypt and Decrypt in C#

Hi,

Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.

thanks,
Gidi.
Nov 17 '05 #1
8 8138
Gidi,

Take a look at the classes in the System.Security.Cryptography
namespace. There are a number of encyrption algorithm implementations there
that you can use.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Gidi" <sh*****@hotmail.com.dontspam> wrote in message
news:EE**********************************@microsof t.com...
Hi,

Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.

thanks,
Gidi.

Nov 17 '05 #2
Unfortunately not... Thankfully though, encryption in .NET is quite easy and
straightforward.

Take a look at http://www.codeproject.com/dotnet/SimpleEncryption.asp for a
run-through on how you can do it. Unfortunately this example is in VB.NET,
however conversion is trivial, or you can just reference the project from
yours.

Brendan
"Gidi" wrote:
Hi,

Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.

thanks,
Gidi.

Nov 17 '05 #3
Thanks Brendan,

I tried this example, and i had problems running it, so i can't really know
how it works...
"Brendan Grant" wrote:
Unfortunately not... Thankfully though, encryption in .NET is quite easy and
straightforward.

Take a look at http://www.codeproject.com/dotnet/SimpleEncryption.asp for a
run-through on how you can do it. Unfortunately this example is in VB.NET,
however conversion is trivial, or you can just reference the project from
yours.

Brendan
"Gidi" wrote:
Hi,

Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.

thanks,
Gidi.

Nov 17 '05 #4
Gidi <sh*****@hotmail.com.dontspam> wrote:
Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.


Encryption and decryption typically work on binary data, not text, and
the .NET libraries are no exception. Look at the CryptoStream class,
and convert your text to/from binary data using the Encoding class.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
SP

"Gidi" <sh*****@hotmail.com.dontspam> wrote in message
news:EE**********************************@microsof t.com...
Hi,

Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.


Try the following:
public static string Decrypt(string encrypted)

{

byte[] data = System.Convert.FromBase64String(encrypted);

byte[] rgbKey = System.Text.ASCIIEncoding.ASCII.GetBytes("12121212 ");

byte[] rgbIV = System.Text.ASCIIEncoding.ASCII.GetBytes("34343434 ");

MemoryStream memoryStream = new MemoryStream(data.Length);

DESCryptoServiceProvider desCryptoServiceProvider = new
DESCryptoServiceProvider();

CryptoStream cryptoStream = new CryptoStream(memoryStream,
desCryptoServiceProvider.CreateDecryptor(rgbKey, rgbIV),
CryptoStreamMode.Read);

memoryStream.Write(data, 0, data.Length);

memoryStream.Position = 0;

string decrypted = new StreamReader(cryptoStream).ReadToEnd();

cryptoStream.Close();

return decrypted;

}

public static string Encrypt(string decrypted)

{

byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(decrypted );

byte[] rgbKey = System.Text.ASCIIEncoding.ASCII.GetBytes("12121212 ");

byte[] rgbIV = System.Text.ASCIIEncoding.ASCII.GetBytes("34343434 ");

MemoryStream memoryStream = new MemoryStream(1024);

DESCryptoServiceProvider desCryptoServiceProvider = new
DESCryptoServiceProvider();

CryptoStream cryptoStream = new CryptoStream(memoryStream,
desCryptoServiceProvider.CreateEncryptor(rgbKey, rgbIV),
CryptoStreamMode.Write);

cryptoStream.Write(data, 0, data.Length);

cryptoStream.FlushFinalBlock();

byte[] result = new byte[(int)memoryStream.Position];

memoryStream.Position = 0;

memoryStream.Read(result, 0, result.Length);

cryptoStream.Close();

return System.Convert.ToBase64String(result);

}

HTH

SP
Nov 17 '05 #6
SP wrote:
Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.

Find one at the bottom. The "MyChoiceOf..." functions reflect more or
less arbitrary choices which I have made for the test -- the choices
taken should be sufficient for most applications.

Note that a more proper use of IV would be to generate it randomly and
include the IV in clear in the encrypted text.

Beware that cryptography is really hard to get right and the sligtest
error often results in a complete compromise of the data thought to be
protected.
Try the following:


There are several things I am not too happy about in that code:

- It uses DES-encryption
- It is designed with the keys in the code
- It uses a constant IV
- It doesn't come with a test (I know, that's a cheap-shot ;)
- It converts data, to and from Base64
- It duplicates the code for creating the en/de-cryption keys
- It only works for strings with a valid ASCII-encoding
- It only works for keys with a valid ASCII-encoding
- It uses the ascii-encoding of key-strings as keys
- It uses a MemoryStream where it's not required

Here is my shot at how to do it. note that it copies the IV and
encrypted-string into a new byte[]. If you are reading/writing to a
stream you can remove that, but you explicitly requested simplicity and
the interface would be much more complicated if the cipher-text and IV
is returned/passed seperatly.

using System.Security.Cryptography;
using System.Text;

class CryptExample
{
public static void InitializeAlgorithm(string secret, HashAlgorithm h,
SymmetricAlgorithm a)
{
byte[] b = System.Text.Encoding.UTF8.GetBytes(secret);
h.TransformFinalBlock(b, 0, b.Length);
byte[] secret_hashed = h.Hash;
byte[] key = new byte[a.KeySize/8];
System.Array.Copy(secret_hashed, 0, key, 0, key.Length);
a.Key = key;
}
public static byte[] Encrypt(string s, SymmetricAlgorithm a)
{
byte[] b = Encoding.UTF8.GetBytes(s);
a.GenerateIV();
byte[] iv = a.IV;
byte[] enc;
using ( ICryptoTransform c = a.CreateEncryptor() )
enc = c.TransformFinalBlock(b, 0, b.Length);
byte[] all = new byte[iv.Length+enc.Length];
System.Array.Copy(iv, 0, all, 0, iv.Length);
System.Array.Copy(enc, 0, all, iv.Length, enc.Length);
return all;
}
public static string Decrypt(byte[] bytes, int offset, int length,
SymmetricAlgorithm a)
{
byte[] iv = new byte[a.BlockSize/8];
System.Array.Copy(bytes, offset, iv, 0, iv.Length);
a.IV = iv;
using ( ICryptoTransform c = a.CreateDecryptor() )
return Encoding.UTF8.GetString(c.TransformFinalBlock(byte s, offset
+ iv.Length, length - iv.Length));
}
public static SymmetricAlgorithm MyChoiceOfEncryptionAlgo()
{
SymmetricAlgorithm alg = Rijndael.Create();
alg.Mode = CipherMode.CBC;
alg.Padding = PaddingMode.PKCS7;
alg.KeySize = 256;
return alg;
}
public static HashAlgorithm MyChoiceOfHashAlgo() { return
SHA512.Create(); }
public static void Main()
{
string secret = "password";
SymmetricAlgorithm enc_algo = MyChoiceOfEncryptionAlgo();
SymmetricAlgorithm dec_algo = MyChoiceOfEncryptionAlgo();

InitializeAlgorithm(secret, MyChoiceOfHashAlgo(), enc_algo);
InitializeAlgorithm(secret, MyChoiceOfHashAlgo(), dec_algo);

for ( int i = 0; i < 1000000; i = (3*i + 1) )
{
string msg = new string('a', i);
byte[] enc = Encrypt(msg, enc_algo);
string dec = Decrypt(enc, 0, enc.Length, dec_algo);
if ( msg != dec )
throw new CryptographicException(string.Format("Plain and
decrypted did not match: {0}!={1}", msg, dec));
}
}
}
--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #7
SP
"Helge Jensen" <he**********@slog.dk> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
SP wrote:
Is there Buid-In fuction in C# that Encrypt and Decrypt strings?
i have a textbox which i'm writing into file, and i want to encrypt it
before writing, i'm not looking for something fancy, just for a simple
Encryption and Decryption function.

Find one at the bottom. The "MyChoiceOf..." functions reflect more or
less arbitrary choices which I have made for the test -- the choices
taken should be sufficient for most applications.

Note that a more proper use of IV would be to generate it randomly and
include the IV in clear in the encrypted text.

Beware that cryptography is really hard to get right and the sligtest
error often results in a complete compromise of the data thought to be
protected.
Try the following:


There are several things I am not too happy about in that code:


It was one of those things that once it worked and it was being used then I
did not want to change it. You make some valid points and I do have some
comments and questions inline.
- It uses DES-encryption
Can you explain why DES is not the best choice.
- It is designed with the keys in the code
How can you decrypt without the keys in your code somewhere. I place the
keys in one place and they are encrypted by an obfuscator. How do you avoid
placing the keys in your code?
- It uses a constant IV
Is it better to use an encrypted and unknown IV or a random but known IV?
You suggested above to use a random IV and store it in clear text.
- It doesn't come with a test (I know, that's a cheap-shot ;)
I did not provide the unit tests. They are in a separate class. Of course it
is easy to test.
- It converts data, to and from Base64
Originally it was to be a license key so it may of needed to be typed in.
- It duplicates the code for creating the en/de-cryption keys
Because I do not provide the Encrypt function in the Release build, only the
Decrypt.
- It only works for strings with a valid ASCII-encoding
- It only works for keys with a valid ASCII-encoding
- It uses the ascii-encoding of key-strings as keys
I knew that the text going in was ASCII but do not want to change anything
at this point. - It uses a MemoryStream where it's not required
I thought the same at the time. I will look at your code to see how to
eliminate the MemoryStream.

Regards

SP.
Here is my shot at how to do it. note that it copies the IV and
encrypted-string into a new byte[]. If you are reading/writing to a
stream you can remove that, but you explicitly requested simplicity and
the interface would be much more complicated if the cipher-text and IV
is returned/passed seperatly.

using System.Security.Cryptography;
using System.Text;

class CryptExample
{
public static void InitializeAlgorithm(string secret, HashAlgorithm h,
SymmetricAlgorithm a)
{
byte[] b = System.Text.Encoding.UTF8.GetBytes(secret);
h.TransformFinalBlock(b, 0, b.Length);
byte[] secret_hashed = h.Hash;
byte[] key = new byte[a.KeySize/8];
System.Array.Copy(secret_hashed, 0, key, 0, key.Length);
a.Key = key;
}
public static byte[] Encrypt(string s, SymmetricAlgorithm a)
{
byte[] b = Encoding.UTF8.GetBytes(s);
a.GenerateIV();
byte[] iv = a.IV;
byte[] enc;
using ( ICryptoTransform c = a.CreateEncryptor() )
enc = c.TransformFinalBlock(b, 0, b.Length);
byte[] all = new byte[iv.Length+enc.Length];
System.Array.Copy(iv, 0, all, 0, iv.Length);
System.Array.Copy(enc, 0, all, iv.Length, enc.Length);
return all;
}
public static string Decrypt(byte[] bytes, int offset, int length,
SymmetricAlgorithm a)
{
byte[] iv = new byte[a.BlockSize/8];
System.Array.Copy(bytes, offset, iv, 0, iv.Length);
a.IV = iv;
using ( ICryptoTransform c = a.CreateDecryptor() )
return Encoding.UTF8.GetString(c.TransformFinalBlock(byte s, offset
+ iv.Length, length - iv.Length));
}
public static SymmetricAlgorithm MyChoiceOfEncryptionAlgo()
{
SymmetricAlgorithm alg = Rijndael.Create();
alg.Mode = CipherMode.CBC;
alg.Padding = PaddingMode.PKCS7;
alg.KeySize = 256;
return alg;
}
public static HashAlgorithm MyChoiceOfHashAlgo() { return
SHA512.Create(); }
public static void Main()
{
string secret = "password";
SymmetricAlgorithm enc_algo = MyChoiceOfEncryptionAlgo();
SymmetricAlgorithm dec_algo = MyChoiceOfEncryptionAlgo();

InitializeAlgorithm(secret, MyChoiceOfHashAlgo(), enc_algo);
InitializeAlgorithm(secret, MyChoiceOfHashAlgo(), dec_algo);

for ( int i = 0; i < 1000000; i = (3*i + 1) )
{
string msg = new string('a', i);
byte[] enc = Encrypt(msg, enc_algo);
string dec = Decrypt(enc, 0, enc.Length, dec_algo);
if ( msg != dec )
throw new CryptographicException(string.Format("Plain and
decrypted did not match: {0}!={1}", msg, dec));
}
}
}
--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #8
SP wrote:
There are several things I am not too happy about in that code:

It was one of those things that once it worked and it was being used then I
did not want to change it. You make some valid points and I do have some
comments and questions inline.


It wasn't that bad, it was just that when I got started looking at the
code more and more things kept drawing my attention...
- It uses DES-encryption

Can you explain why DES is not the best choice.


DES is not "secure". it's keys are 56-bits, modern CPU's can brute force
DES faster than you can change the keys, custom hardware can do it in
minutes. Rinjdael (now AES) have longer key-lengths and generally
considered much more resistant to attacks.
- It is designed with the keys in the code


How can you decrypt without the keys in your code somewhere. I place the
keys in one place and they are encrypted by an obfuscator. How do you avoid
placing the keys in your code?


The keys were actually duplicated, as the strings "1234...".

To avoid having the keys in the code, either prompt for them, have them
on disk or use any other means of input. Even if you know them to be
constant, have them in a file or something, so you can provide different
keys to different people.

BTW: an obfuscator will not really help against any, even just slightly,
qualified attacker.
- It uses a constant IV


Is it better to use an encrypted and unknown IV or a random but known IV?
You suggested above to use a random IV and store it in clear text.


The IV isn't secret, it's used to seed the encryption. No secrecy is
lost by transferring it it clear-text, nor is any secrecy gained by
obscuring it or "encrypting" it.

Choosing a random IV gives you non-deterministic cryptography -- that
is, multiple encryptions of the same clear is encrypted to different
cipher-texts.
- It doesn't come with a test (I know, that's a cheap-shot ;)


I did not provide the unit tests. They are in a separate class. Of course it
is easy to test.


Good, cryptographic code should almost always be unit-tested, it's
really hard to debug by inspecting the encrypted data ;)
- It converts data, to and from Base64


Originally it was to be a license key so it may of needed to be typed in.


En/De-cryption should be a separate concen from what format the
input-data is in. If you need to Base64 convert somewhere, just do it on
the in/output of the de/en-cryption.
- It duplicates the code for creating the en/de-cryption keys


Because I do not provide the Encrypt function in the Release build, only the
Decrypt.


That doesn't prevent you from having a separate function for creating
the en/de-cryption keys. (http://c2.com/cgi/wiki?OnceAndOnlyOnce)
- It only works for strings with a valid ASCII-encoding
- It only works for keys with a valid ASCII-encoding
- It uses the ascii-encoding of key-strings as keys


I knew that the text going in was ASCII but do not want to change anything
at this point.


Fine, note that valud ASCII-text is encoded exactly the same in ASCII
and UTF8.

Using the ascii-encoding of key-strings directly as keys is frowned upon
since at dramatically reduces the used keyspace. Hashing the keys
removes this problem.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #9

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

Similar topics

1
by: wqhdebian | last post by:
As far as I know,when encrypt or decrypt ,a key must first be got,and the key is first generate by a tool or from SecurityRandom,that means I can not generate the same key with the same input.Does...
4
by: Spikinsson | last post by:
I'm looking for a good decrypt/encrypt function, all I want is a function in this form: char* encrypt(char* normal) { ... return encrypted; } and
0
by: Mark Hanford | last post by:
I've been setting up a new MySQL/PHP site which will contain store some CC details, and have been wondering how to pass the keys. CC's are written in a similar way to: INSERT INTO cc (ccName,...
1
by: Benoît | last post by:
Hi, I have generated two keys : "C:>openssl req -nodes -new -x509 -keyout ben.key -out ben.crt -days 3650" I try to encrypt/decrypt a string like "JOHN" with these asymetrics keys. With the...
7
by: Matthias S. | last post by:
Hi, I had a look at the vast information on encryption in the MSDN and got pretty confused. All I want to do is to encrypt a string into an encrypted string and later decrypt that (encrypted)...
4
by: Hrvoje Voda | last post by:
Does anyone knows a good example of how to encrypt/decrypt a string? Hrcko
8
by: toupeira23 | last post by:
Hello, I'm trying to encrypt passwords in my app. After discovering that there's no simple function to do this, I wrote a wrapper class which decodes a string using UTF8, encrypts it with...
4
by: Islamegy® | last post by:
I give up.. I tried everything to encrypt querystring and decrypt it back but this never success.. i use RSA encryption. I always get excption when Convert fromBase64String so i tried...
3
by: JDeats | last post by:
I have some .NET 1.1 code that utilizes this technique for encrypting and decrypting a file. http://support.microsoft.com/kb/307010 In .NET 2.0 this approach is not fully supported (a .NET 2.0...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.