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[i]);
}
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]
Jon Skeet [C# MVP] wrote:
Matthias S. <matthias@_e_m_v_o_i_d_.de> wrote:
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).