In c#, there is a namespace called System.Security.Cryptography
and there are many classes in this namespace, which help developers encrypt and decrypt data. However, always they take byte[]
array and they return byte[]
array. So, as a developer, you have to always write a library to get the clear-text, turn it into byte of arrays, encrypt it, then turn the cipher array into an string, and return it.
I've talked to some other PHP and Java developers, and they told me that they have to undergo the same process there too. I haven't seen those languages though.
My question is, why frameworks like .NET framework, don't provide an straightforward mechanism for encryption and decryption?
I mean, from the point of view of a developer, cryptography means a black box into which you pass a string, and from which you will get an string, without the need to get into the complexity of creating streams like CryptoStream
and without the need to converting strings into bytes of arrays, etc.
For example, look at this simple encryption example, taken from Microsoft's MSDN:
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an Rijndael object
// with the specified key and IV.
using (Rijndael rijAlg = Rijndael.Create())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
This is just not simple and easy, and I think there should be a class in .NET Framework like TripleDesCryptoHelper
with two methods as follow:
public string Encrypt(string clearText)
{
// Doing the cryptography stuff here
return cipherText;
}
public string Decrypt(string cipherText)
{
// Doing the cryptography stuff here
return clearText;
}