String encryption in C# and Objective c - c#

I am building a iPhone app which uses c# web services. My c# web services takes user details and validates against my DB and returns xml files.
So Now the issue is how to encrypt user details(username and password are 10chars each) in objective c and decrypt in C#.
I am very new to cryptography, which method is the best. will it be possible to encrypt in Objective c and Decrypt in C#.
thanks..

Thanks for the rapid replies. I appreciate your help. I found a blog which explains my problem. Here is the link for it.
http://dotmac.rationalmind.net/2009/02/aes-interoperability-between-net-and-iphone/
I am implementing it now. I will let you know the status soon.
Thanks a lot..
Happy coding..

On the assumption that you're encrypting this information in order to protect it over the network, the best solution is to connect over SSL. This will address the problem without creating new complexities in the code. SSL handling is generally available in both .NET and Cocoa.
Is there some other reason that you're trying to encrypt this data?

The following is from the The CSharp Cookbook. It is about as straight forwand an example as exists. You would of course have to port the encrypt portion to Objective C, but so long as you used the same Key, it should generate the same result.
You need to use Rijndael cipher which is available here in ObjC compatible code
public static void EncDecString()
{
string encryptedString = CryptoString.Encrypt("MyPassword");
Console.WriteLine("encryptedString: " + encryptedString);
// get the key and IV used so you can decrypt it later
byte [] key = CryptoString.Key;
byte [] IV = CryptoString.IV;
CryptoString.Key = key;
CryptoString.IV = IV;
string decryptedString = CryptoString.Decrypt(encryptedString);
Console.WriteLine("decryptedString: " + decryptedString);
}
public sealed class CryptoString
{
private CryptoString() {}
private static byte[] savedKey = null;
private static byte[] savedIV = null;
public static byte[] Key
{
get { return savedKey; }
set { savedKey = value; }
}
public static byte[] IV
{
get { return savedIV; }
set { savedIV = value; }
}
private static void RdGenerateSecretKey(RijndaelManaged rdProvider)
{
if (savedKey == null)
{
rdProvider.KeySize = 256;
rdProvider.GenerateKey();
savedKey = rdProvider.Key;
}
}
private static void RdGenerateSecretInitVector(RijndaelManaged rdProvider)
{
if (savedIV == null)
{
rdProvider.GenerateIV();
savedIV = rdProvider.IV;
}
}
public static string Encrypt(string originalStr)
{
// Encode data string to be stored in memory
byte[] originalStrAsBytes = Encoding.ASCII.GetBytes(originalStr);
byte[] originalBytes = {};
// Create MemoryStream to contain output
MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length);
RijndaelManaged rijndael = new RijndaelManaged();
// Generate and save secret key and init vector
RdGenerateSecretKey(rijndael);
RdGenerateSecretInitVector(rijndael);
if (savedKey == null || savedIV == null)
{
throw (new NullReferenceException(
"savedKey and savedIV must be non-null."));
}
// Create encryptor, and stream objects
ICryptoTransform rdTransform =
rijndael.CreateEncryptor((byte[])savedKey.Clone(),
(byte[])savedIV.Clone());
CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform,
CryptoStreamMode.Write);
// Write encrypted data to the MemoryStream
cryptoStream.Write(originalStrAsBytes, 0, originalStrAsBytes.Length);
cryptoStream.FlushFinalBlock();
originalBytes = memStream.ToArray();
// Release all resources
memStream.Close();
cryptoStream.Close();
rdTransform.Dispose();
rijndael.Clear();
// Convert encrypted string
string encryptedStr = Convert.ToBase64String(originalBytes);
return (encryptedStr);
}
public static string Decrypt(string encryptedStr)
{
// Unconvert encrypted string
byte[] encryptedStrAsBytes = Convert.FromBase64String(encryptedStr);
byte[] initialText = new Byte[encryptedStrAsBytes.Length];
RijndaelManaged rijndael = new RijndaelManaged();
MemoryStream memStream = new MemoryStream(encryptedStrAsBytes);
if (savedKey == null || savedIV == null)
{
throw (new NullReferenceException(
"savedKey and savedIV must be non-null."));
}
// Create decryptor, and stream objects
ICryptoTransform rdTransform =
rijndael.CreateDecryptor((byte[])savedKey.Clone(),
(byte[])savedIV.Clone());
CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform,
CryptoStreamMode.Read);
// Read in decrypted string as a byte[]
cryptoStream.Read(initialText, 0, initialText.Length);
// Release all resources
memStream.Close();
cryptoStream.Close();
rdTransform.Dispose();
rijndael.Clear();
// Convert byte[] to string
string decryptedStr = Encoding.ASCII.GetString(initialText);
return (decryptedStr);
}
}
I can't speak regarding the Objective C implementation of Rijndael cipher, but I have used this(C#) code for the basis of some production work and it has worked wonderfully.

Your question is very vague, but in short; yes, it is possible. You will need to figure out what the expectations of your cryptography are (high security or high speed?) and then weigh the benefits of various algorthms and their implementation difficulties in Objective-C and C#.

I don't know Objective C, but for the C# decryption, look into the various CryptoServiceProviders in System.Security.Cryptography.
Here is one example I wrote using TripleDES:
public class TripleDES
{
private byte[] mbKey;
private byte[] mbIV;
private TripleDESCryptoServiceProvider tdProvider = new TripleDESCryptoServiceProvider();
private UTF8Encoding UTEncode = new UTF8Encoding();
// Key: **YOUR KEY**
// Project IV: **YOUR IV**
public TripleDES(string strKey, string strIV)
{
mbKey = UTEncode.GetBytes(strKey);
mbIV = UTEncode.GetBytes(strIV);
}
public TripleDES()
{
//
// TODO: Add constructor logic here
//
}
public string EncryptToString(string strInput)
{
return Convert.ToBase64String(this.EncryptToBytes(strInput));
}
public byte[] EncryptToBytes(string strInput)
{
byte[] bInput = UTEncode.GetBytes(strInput);
byte[] bOutput = ProcessInput(bInput, tdProvider.CreateEncryptor(mbKey, mbIV));
return bOutput;
}
public string DecryptToString(string strInput)
{
return UTEncode.GetString(DecryptToBytes(strInput));
}
public byte[] DecryptToBytes(string strInput)
{
byte[] bInput = Convert.FromBase64String(strInput);
byte[] bOutput = ProcessInput(bInput, tdProvider.CreateDecryptor(mbKey, mbIV));
return bOutput;
}
private byte[] ProcessInput(byte[] input, ICryptoTransform ctProcessor)
{
MemoryStream memStream = new MemoryStream();
CryptoStream crpStream = new CryptoStream(memStream, ctProcessor, CryptoStreamMode.Write);
crpStream.Write(input, 0, input.Length);
crpStream.FlushFinalBlock();
memStream.Position = 0;
byte[] output;
output = new byte[memStream.Length];
memStream.Read(output, 0, output.Length);
memStream.Close();
crpStream.Close();
return output;
}
}
}

Related

C# Encryption Information

We are using below code to encrypt/decrypt text to store some sensitive information into our database.
public static string Encrypt(string inputText)
{
const string ENCRYPTION_KEY = "MY_KEY";
byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());
System.Security.Cryptography.RijndaelManaged rijndaelCipher = null;
byte[] plainText = null;
System.Security.Cryptography.PasswordDeriveBytes SecretKey = null;
try
{
rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
plainText = Encoding.Unicode.GetBytes(inputText);
SecretKey = new System.Security.Cryptography.PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
using (System.Security.Cryptography.ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
{
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
catch
{
throw;
}
finally
{
rijndaelCipher = null;
plainText = null;
plainText = null;
}
}
public static string Decrypt(string inputText)
{
string ENCRYPTION_KEY = "MY_KEY";
byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());
System.Security.Cryptography.RijndaelManaged rijndaelCipher = null;
byte[] encryptedData = null;
byte[] plainText = null;
try
{
rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
encryptedData = Convert.FromBase64String(inputText);
System.Security.Cryptography.PasswordDeriveBytes secretKey = new System.Security.Cryptography.PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
using (System.Security.Cryptography.ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(encryptedData))
{
using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
{
plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}
catch
{
return "";
}
finally
{
rijndaelCipher = null;
encryptedData = null;
plainText = null;
}
}
I am not original developer who wrote this code, I need to write some documentation related to security so want to know the exact name of above algorithm. Can someone tell me what is the exact name of above methodology to encrypt/decrypt text. Like MD5, SHA256, AES etc.
I googled a lot but not able to find proper confident answer.
Thanks.
Rijndael is the algorithm that won AES competition, but only for the version with 128 bits of BlockSize. Microsoft doc states that the default value for RijndaelManaged class is 128 so this code uses AES-256-CBC with PKCS7 padding (the key is 32 bytes and no mode is specified).
However this code is very unsecure: you should use a mode such as GCM, or CBC/CTR plus a checksum, and the key should never be derivated from a simple hardcoded ascii string, no matter how long or complex it is, with the salt being a simple copy of it. Finally the IV should be random and saved along the cipherText and not derivated from the key, otherwise attacks common for ECB mode could be applied here as well.
PS: RijndaelManaged is marked as obsolete and Aes or AesCryptoServiceProvider should be used.

AES Padding is Invalid And Cannot Be Removed

I am using AES criptography algorithms to encrypt and decrypt my values in my project. My code works almost everytime but sometimes I get Padding is invalid and cannot be removed error. My project is ASP .NET Core 3.1 project and it's published on IIS Server 8.5.
As said at Padding is invalid and cannot be removed? question asked 9 years ago, my keys and salts are always set 128 bits and padding mode is always set to PKCS#7 like this code: aes.Padding = PaddingMode.PKCS7;.
But sometimes, I got this error. After debugging my code with the same key, salt and decrypted value I didn't get any error and my code works fine for another 10 hours or so. I have no idea why my code behaves like this but I couldn't find any solution.
My Constructor:
public void KriptoAlgoritmasiniAyarla(string password, string salt, SymmetricAlgorithm algorithm)
{
if (password == null) throw new ArgumentNullException(nameof(password));
if (salt == null) throw new ArgumentNullException(nameof(salt));
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
var rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
var rgbIv = rgb.GetBytes(algorithm.BlockSize >> 3);
_sifreleyici = algorithm.CreateEncryptor(rgbKey, rgbIv);
_desifreleyici = algorithm.CreateDecryptor(rgbKey, rgbIv);
}
My encrption code:
public byte[] ByteDizisineSifrele(string plainText)
{
try
{
byte[] encrypted;
// Create a new AesManaged.
using (AesManaged aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
// Create MemoryStream
using (MemoryStream ms = new MemoryStream())
{
// Create crypto stream using the CryptoStream class. This class is the key to encryption
// and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream
// to encrypt
using (CryptoStream cs = new CryptoStream(ms, _sifreleyici, CryptoStreamMode.Write))
{
// Create StreamWriter and write data to a stream
using (StreamWriter sw = new StreamWriter(cs))
sw.Write(plainText);
encrypted = ms.ToArray();
}
}
}
// Return encrypted data
return encrypted;
}
catch (Exception exp)
{
throw exp;
}
}
My decryption code:
public string ByteDizisiDesifreEt(byte[] cipherText)
{
try
{
string plaintext = null;
// Create AesManaged
using (AesManaged aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
// Create the streams used for decryption.
using (MemoryStream ms = new MemoryStream(cipherText))
{
// Create crypto stream
using (CryptoStream cs = new CryptoStream(ms, _desifreleyici, CryptoStreamMode.Read))
{
// Read crypto stream
using (StreamReader reader = new StreamReader(cs))
plaintext = reader.ReadToEnd();
}
}
}
return plaintext;
}
catch (Exception exp)
{
throw exp;
}
}
Probably because you are reusing the same ICryptoTransform objects (_sifreleyici and _desifreleyici). At some point, the transform object can't be reused anymore and therefore the interface has a property to determine that. The ICryptoTransform.CanReuseTransform property.
Consequently, you need to check this property and recreate the objects when you get false.
Example
private readonly byte[] Key, IV;
public void KriptoAlgoritmasiniAyarla(
string password,
string salt,
SymmetricAlgorithm algorithm)
{
// ...
Key = // Get the key..
IV = // Get the IV..
}
private ICryptoTransform encryptor;
private ICryptoTransform Encryptor
{
get
{
if (encryptor == null || !encryptor.CanReuseTransform)
{
encryptor?.Dispose();
encryptor = Algorithm.CreateEncryptor(Key, IV);
}
return encryptor;
}
}
private ICryptoTransform decryptor;
private ICryptoTransform Decryptor
{
get
{
if (decryptor == null || !decryptor.CanReuseTransform)
{
decryptor?.Dispose();
decryptor = Algorithm.CreateDecryptor(Key, IV);
}
return decryptor;
}
}
Then use these two properties in the related methods to create the CryptoStream.
Alternative
I'd like to propose the code below as an alternative that can be used with the classes that derive from the SymmetricAlgorithm abstract class.
public class SymmetricCrypto<T> : IDisposable where T : SymmetricAlgorithm, new()
{
private readonly T Algorithm = new T();
public SymmetricCrypto()
{
Algorithm.GenerateKey();
Algorithm.GenerateIV();
}
public SymmetricCrypto(byte[] key, byte[] iv)
{
Algorithm.Key = key;
Algorithm.IV = iv;
}
public SymmetricCrypto(string pass)
{
var bytes = Encoding.UTF8.GetBytes(pass);
var rfc = new Rfc2898DeriveBytes(pass,
new SHA256Managed().ComputeHash(bytes), 1000);
Algorithm.Key = rfc.GetBytes(Algorithm.LegalKeySizes[0].MaxSize / 8);
Algorithm.IV = rfc.GetBytes(Algorithm.LegalBlockSizes[0].MinSize / 8);
}
public SymmetricCrypto(byte[] pass)
{
var rfc = new Rfc2898DeriveBytes(pass,
new SHA256Managed().ComputeHash(pass), 1000);
Algorithm.Key = rfc.GetBytes(Algorithm.LegalKeySizes[0].MaxSize / 8);
Algorithm.IV = rfc.GetBytes(Algorithm.LegalBlockSizes[0].MinSize / 8);
}
public byte[] Encrypt(string input) =>
Transform(Encoding.UTF8.GetBytes(input), Algorithm.CreateEncryptor());
public string Decrypt(byte[] input) =>
Encoding.UTF8.GetString(Transform(input, Algorithm.CreateDecryptor()));
private byte[] Transform(byte[] input, ICryptoTransform cryptoTrans)
{
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, cryptoTrans, CryptoStreamMode.Write))
{
cs.Write(input, 0, input.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
public void Dispose() => Algorithm.Dispose();
}
Usage:
void SomeCaller()
{
using (var crypt = new SymmetricCrypto<AesManaged>("password"))
{
var bytes = crypt.Encrypt("Plain Text....");
// ...
var plainText = crypt.Decrypt(bytes);
// ...
}
}

"Padding is invalid and cannot be removed" during decryption

First, I realize there are dozens of other posts that have answers to this question and I have read and tried them all. I still can't seem to get past this issue so am looking for a little help from somebody that knows more about crypto than I do.
Second, the code I am going to share is legacy and because I am not a crypto expert it is still not 100% clear on what everything means. It may be that some or all of this code is total rubbish and should be scrapped; however, there are a lot of other systems already using it and have stored encrypted values that have gone through this code. Changing things like the crypto algorithm is not exactly an option at this point. With that said, the private methods are the legacy code as well as the testing values (i.e. the encryption key) are all things that can't change. The two public static methods are what is new and likely causing problems, but I can't seem to figure it out.
On with the code......
class Program
{
public static string Encrypt(string key, string toEncrypt)
{
var keyArray = Convert.FromBase64String(key);
var info = Encoding.ASCII.GetBytes(toEncrypt);
var encrypted = Encrypt(keyArray, info);
return Encoding.ASCII.GetString(encrypted);
}
public static string Decrypt(string key, string cipherString)
{
var keyArray = Convert.FromBase64String(key);
var cipherText = Encoding.ASCII.GetBytes(cipherString);
var decrypted = Decrypt(keyArray, cipherText);
return Encoding.ASCII.GetString(decrypted);
}
private static byte[] Encrypt(byte[] key, byte[] info)
{
using (var cipher = Aes.Create())
{
cipher.Key = key;
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.ISO10126;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, cipher.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(info, 0, info.Length);
}
var ciphertext = ms.ToArray();
var message = new byte[cipher.IV.Length + ciphertext.Length];
cipher.IV.CopyTo(message, 0);
ciphertext.CopyTo(message, cipher.IV.Length);
return message;
}
}
}
private static byte[] Decrypt(byte[] key, byte[] ciphertext)
{
using (var cipher = Aes.Create())
{
cipher.Key = key;
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.ISO10126;
var ivSize = cipher.IV.Length;
var iv = new byte[ivSize];
Array.Copy(ciphertext, iv, ivSize);
cipher.IV = iv;
var data = new byte[ciphertext.Length - ivSize];
Array.Copy(ciphertext, ivSize, data, 0, data.Length);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, cipher.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
}
return ms.ToArray();
}
}
}
static void Main(string[] args)
{
var newEncryptionKey = Guid.NewGuid().ToString().Replace("-", string.Empty);
var encryptedValue = Encrypt(newEncryptionKey, "test");
Console.WriteLine($"New encrypted value: {encryptedValue}");
var decryptedValue = Decrypt(newEncryptionKey, encryptedValue);
Console.WriteLine($"New decrypted value: {decryptedValue}");
}
}
So there it is. Basically, I am trying to use a test string of "test" and encrypt it using a GUID as a key. Again, I didn't choose this key and there are encrypted values already using a GUID as a key so I can't change that if at all possible. The encryption works fine, but when I go to do the decryption, I get the exception noted in the title of this question.
Any help would be GREATLY appreciated.
You can't just convert a byte[] of ciphertext to ASCII. It doesn't work like that. Character encodings are scary beasts and should not be muddled with if you don't understand them. I don't think there is a real person alive that does ;)
What you should do instead is return your result as base64, which is still a collection of ASCII characters but they are safe to be moved around as a string, and don't result in the loss of any characters.
See the modified code below:
public static string Encrypt(string key, string toEncrypt)
{
var keyArray = Convert.FromBase64String(key);
var info = Encoding.ASCII.GetBytes(toEncrypt);
var encrypted = Encrypt(keyArray, info);
return Convert.ToBase64String(encrypted);
}
public static string Decrypt(string key, string cipherString)
{
var keyArray = Convert.FromBase64String(key);
var cipherText = Convert.FromBase64String(cipherString);
var decrypted = Decrypt(keyArray, cipherText);
return Encoding.ASCII.GetString(decrypted);
}

Length of the data to Encrypt is invalid

Getting Exception " length of the data to ENCRYPTION is invalid".
private static readonly byte[] salt = Encoding.ASCII.GetBytes("S#sh#kt# VMS");
public static string Encrypt(string textToEncrypt, string encryptionPassword)
{
byte[] encryptedBytes = null;
try
{
var algorithm = GetAlgorithm(encryptionPassword);
algorithm.Padding = PaddingMode.None;
using (ICryptoTransform encryptor = algorithm.CreateEncryptor(algorithm.Key, algorithm.IV))
{
byte[] bytesToEncrypt = Encoding.UTF8.GetBytes(textToEncrypt);
encryptedBytes = InMemoryCrypt(bytesToEncrypt, encryptor);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Convert.ToBase64String(encryptedBytes);
}
// Performs an in-memory encrypt/decrypt transformation on a byte array.
private static byte[] InMemoryCrypt(byte[] data, ICryptoTransform transform)
{
MemoryStream memory = new MemoryStream();
using (Stream stream = new CryptoStream(memory, transform, CryptoStreamMode.Write))
{
stream.Flush();
stream.Write(data, 0, data.Length);
//stream.FlushFinalBlock();
}
return memory.ToArray();
}
private static RijndaelManaged GetAlgorithm(string encryptionPassword)
{
// Create an encryption key from the encryptionPassword and salt.
var key = new Rfc2898DeriveBytes(encryptionPassword, salt);
// Declare that we are going to use the Rijndael algorithm with the key that we've just got.
var algorithm = new RijndaelManaged();
int bytesForKey = algorithm.KeySize/8;
int bytesForIV = algorithm.BlockSize/8;
algorithm.Key = key.GetBytes(bytesForKey);
algorithm.IV = key.GetBytes(bytesForIV);
return algorithm;
}
And the decryption routine is:
public static string Decrypt(string encryptedText, string encryptionPassword)
{
var algorithm = GetAlgorithm(encryptionPassword);
algorithm.Padding = PaddingMode.PKCS7;
byte[] descryptedBytes;
using (ICryptoTransform decryptor = algorithm.CreateDecryptor(algorithm.Key, algorithm.IV))
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
descryptedBytes = InMemoryCrypt(encryptedBytes, decryptor);
}
return Encoding.UTF8.GetString(descryptedBytes);
}
PaddingMode.None requires that the input is a multiple of the block size. Use somethink like PaddingMode.PKCS7 instread.
A few other issues with your code:
A constant doesn't make a good salt
The constant salt together with deterministic derivation of the IV from the password means that you're reusing (Key, IV) pairs, which should not be done
You don't add authentication/some kind of MAC. That often leads to padding oracles or similar attacks
You read more the native size from the PBKDF2 output. That halves your key derivation speed without slowing down an attacker.

Is there any difference between implementation of Triple DES in C# and Java? Java gives error wrong IV size

In our application we are using Triple DES to encrypt and decrypt the data. We have the enc/dec code in C# which uses 24 byte key and 12 byte IV which works fine. Now we want to implement same code in java but when I use 12 byte IV, I get an error in java saying wrong IV size. When I googled around, I came to know that java uses 8 byte IV. Now I am confused as how come there is implementation difference in C# and JAVA for triple DES. Or am I missing anything?
This is something similar to our encryption code
class cTripleDES
{
// define the triple des provider
private TripleDESCryptoServiceProvider m_des = new TripleDESCryptoServiceProvider();
// define the string handler
private UTF8Encoding m_utf8 = new UTF8Encoding();
// define the local property arrays
private byte[] m_key;
private byte[] m_iv;
public cTripleDES(byte[] key, byte[] iv)
{
this.m_key = key;
this.m_iv = iv;
}
public byte[] Encrypt(byte[] input)
{
return Transform(input,
m_des.CreateEncryptor(m_key, m_iv));
}
public byte[] Decrypt(byte[] input)
{
return Transform(input,
m_des.CreateDecryptor(m_key, m_iv));
}
public string Encrypt(string text)
{
byte[] input = m_utf8.GetBytes(text);
byte[] output = Transform(input,
m_des.CreateEncryptor(m_key, m_iv));
return Convert.ToBase64String(output);
}
public string Decrypt(string text)
{
byte[] input = Convert.FromBase64String(text);
byte[] output = Transform(input,
m_des.CreateDecryptor(m_key, m_iv));
return m_utf8.GetString(output);
}
private byte[] Transform(byte[] input,
ICryptoTransform CryptoTransform)
{
// create the necessary streams
MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream,
CryptoTransform, CryptoStreamMode.Write);
// transform the bytes as requested
cryptStream.Write(input, 0, input.Length);
cryptStream.FlushFinalBlock();
// Read the memory stream and
// convert it back into byte array
memStream.Position = 0;
byte[] result = memStream.ToArray();
// close and release the streams
memStream.Close();
cryptStream.Close();
// hand back the encrypted buffer
return result;
}
}
This is how we are utilizing it:
string IVasAString = "AkdrIFjaQrRQ";
byte[] iv = Convert.FromBase64String(IVasAString);
byte[] key = ASCIIEncoding.UTF8.GetBytes(KEY);
// instantiate the class with the arrays
cTripleDES des = new cTripleDES(key, iv);
string output = des.Encrypt("DATA TO BE ENCRYPTED");
TripleDES has a 64-bit block size. You need to use an 8 byte IV in C#.
Got the answer.
decodeBase64 method from apache common framework (commons.codec.binary.Base64) does the necessary.
Thanks mfanto for the heads up.!

Categories