I have to encrypt data in c# same as the java. I did not get same output from the c#, please guide me where I am doing mistake
Here is the java code
DESedeKeySpec keyspec
= new DESedeKeySpec(key.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(EncryptionAlgorithm.DESede.name());
SecretKey deskey = keyfactory.generateSecret(keyspec);
// Create an 8-byte initialization vector
byte[] iv = new byte[]{(byte) 0x39, 0x39, 0x39, (byte) 0x39, 0x39, 0x39, 0x39, 0x39};
IvParameterSpec ivVector = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(EncryptionAlgorithm.DESede.name() + "/" + EncryptionMode.CBC.name() + "/"
+ EncryptionPadding.PKCS5Padding.name());
byte[] ciphertext = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, deskey, ivVector);
ciphertext = cipher.doFinal(pass.getBytes());
} catch (Exception e) {
}
Here is my C# code..
public string Encrypt(string toEncrypt, bool useHashing,string key)
{
byte[] keyArray;
byte[] toEncryptArray = Encoding.ASCII.GetBytes(toEncrypt);
string retvalue = "";
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.ASCII.GetBytes(key));
//Always release the resources and flush data
// of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = Encoding.ASCII.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.IV = new byte[] { 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39 };
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.PKCS7;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateEncryptor(keyArray, keyArray), CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cryptoStream))
{
writer.Write(toEncrypt);
cryptoStream.FlushFinalBlock();
writer.Flush();
retvalue = BitConverter.ToString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length).Replace("-","");
writer.Close();
}
cryptoStream.Close();
}
memoryStream.Close();
}
return retvalue;
}
DESCryptoServiceProviderandTripleDESCryptoServiceProviderare different. Are you sure you have chosen the proper one?