Encrypt a string to a string and vice versa

  • Thread starter Thread starter Matthias S.
  • Start date Start date
M

Matthias S.

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) string again to a human readable
form. Can't be that difficult :).

Could you send me please into the right direction. Thanks in advance.
 
Hi Matthias,

..NET provides cryptographics services in class contained in the
System.Security.Cryptography namespace.

First, you need to decide on which type of encryption you would like to use
- basically, there are three: symmetric, asymmetric, and hashing. From what
you said, you should go for either of the first two. Go for symmetric for
more performance, and asymmetric if you need more security.

Once that is decided, you create an instance of the required
CryptoServiceProvider in the required class. For example,
System.Security.Cryptography.RSACryptoServiceProvider which derives from
System.Security.Cryptography.AsymmetricAlgorithm and then use the required
method (eg. Enrypt). Note that most of these method accept a Stream or an
array of bytes, so you will have to use UTF8 encoding class to convert your
string.

Check out this MSDN link for a detailed implementation
http://msdn.microsoft.com/library/en-us/cpguide/html/cpconencryptingdecryptingdata.asp

Let me know if I could help more.

HTH,
Rakesh Rajan
 
Matthias S. said:
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) string again to a human readable
form. Can't be that difficult :).

Could you send me please into the right direction. Thanks in advance.

The encryption libraries in .NET (like most encryption libraries) are
from binary to binary. So, you need to:

1) Convert your string to binary: use an Encoding and its GetBytes
method. I would suggest Encoding.UTF8.

2) Encrypt the binary data. Look at CryptoStream for some sample code.
You need to make sure you call FlushFinalBlock or Close - Dispose isn't
correctly implemented in CryptoStream.

3) Convert the resulting binary data into a string again. For this, I'd
suggest using Base64 - Convert.ToBase64String.


To decrypt, just reverse - use Convert.FromBase64String, then a
CryptoStream, then Encoding.UTF8.GetString(bytes).
 
hi john,

thanks for your reply which was of big help. So far I managed to encrypt
the string but running into problems when decrypting:

Here is how I encrypt:
+++
// sSource contains the string to be encrypted
UTF8Encoding utf8 = new UTF8Encoding();
byte[] utf8Bytes = utf8.GetBytes(sSource);

// encrypt
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(),
CryptoStreamMode.Write);

for (int i = 0; i < utf8Bytes.Length; i++) {
cs.WriteByte(utf8Bytes);
}

cs.Flush();
// return the encrypted string
return Convert.ToBase64String(ms.ToArray());
+++

it seems to work fine. I will be knowing it once I've managed to decrypt
the whole thing again.

Here is how I'd like to decrypt:
+++
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(sSource));
CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(),
CryptoStreamMode.Read);

for (int i = 0; i < ms.Length; i++) {
// the next line with throw a CryptographicException with the
// message: "Padding is invalid and can not be removed."
cs.ReadByte();
}
+++

Besides that I figured that the CryptoStream does not support a Length
property. So how am I can I get my cs variable into a byte[]?

Thanks for any help again!


kind regards,

matthias

--

I love deadlines. I like the whooshing sound they make as they fly by.
[Douglas Adams]
 
Matthias S. said:
thanks for your reply which was of big help. So far I managed to encrypt
the string but running into problems when decrypting:

Here is how I encrypt:
+++
// sSource contains the string to be encrypted
UTF8Encoding utf8 = new UTF8Encoding();
byte[] utf8Bytes = utf8.GetBytes(sSource);

// encrypt
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(),
CryptoStreamMode.Write);

for (int i = 0; i < utf8Bytes.Length; i++) {
cs.WriteByte(utf8Bytes);
}

cs.Flush();


You're neither calling Close() nor FlushFinalBlock() on the
CryptoStream. That may well be the problem.

By the way: using ReadByte and WriteByte is a pretty painful way of
reading and writing data. Use the forms which read and write blocks of
data at a time, paying attention to the return value from Read.
 
hi john,

sorry if I didn't make myself clear enough. The encryption method works
fine (at least I don't get an exception anywhere, if the string is
correctly encryption is left aside). The problem lies in the
Decryption-part of the task, where I'm just creating a MemoryStream by
converting the result of my previously mentioned encryption method using
Convert.FromBase64String().

The problem is, as soon as I call ReadByte on the CryptoStream, I get the
CryptographicException mentioned below.

+++
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(sSource));
CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(),
CryptoStreamMode.Read);

for (int i = 0; i < ms.Length; i++) {
// the next line with throw a CryptographicException with the
// message: "Padding is invalid and can not be removed."
cs.ReadByte();
+++

As to your answer on the Read-Method, I actually don't know how to Read
*anything* from the stream if I can't retrieve the current Position or
Length (both not provided in the CryptoStream).

btw, big thanks to you for helping me out on this one.

kind regards,

matthias

--

I love deadlines. I like the whooshing sound they make as they fly by.
[Douglas Adams]




Matthias S. said:
thanks for your reply which was of big help. So far I managed to encrypt
the string but running into problems when decrypting:

Here is how I encrypt:
+++
// sSource contains the string to be encrypted
UTF8Encoding utf8 = new UTF8Encoding();
byte[] utf8Bytes = utf8.GetBytes(sSource);

// encrypt
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(),
CryptoStreamMode.Write);

for (int i = 0; i < utf8Bytes.Length; i++) {
cs.WriteByte(utf8Bytes);
}

cs.Flush();



You're neither calling Close() nor FlushFinalBlock() on the
CryptoStream. That may well be the problem.

By the way: using ReadByte and WriteByte is a pretty painful way of
reading and writing data. Use the forms which read and write blocks of
data at a time, paying attention to the return value from Read.
 
Matthias S. said:
sorry if I didn't make myself clear enough. The encryption method works
fine (at least I don't get an exception anywhere, if the string is
correctly encryption is left aside). The problem lies in the
Decryption-part of the task, where I'm just creating a MemoryStream by
converting the result of my previously mentioned encryption method using
Convert.FromBase64String().

The problem is, as soon as I call ReadByte on the CryptoStream, I get the
CryptographicException mentioned below.

The problem is that the encryption *hasn't* worked - you've not got all
the data. You didn't get an exception, but you didn't get the right
data, either.
 
Back
Top