2

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;
}
2
  • DESCryptoServiceProvider and TripleDESCryptoServiceProvider are different. Are you sure you have chosen the proper one? Commented Jul 16, 2016 at 5:25
  • i tried with both the des and 3des.. i did not get the result Commented Jul 16, 2016 at 6:06

2 Answers 2

1

You're flushing the buffers in the wrong order in the C# version. First you flush the CryptoStream, signalling that you're done with the crypto operations, then you flush the the StreamWriter, signaling that you're now down writing the stream, after you've finished the final crypto block during the flush operation.

If you switch these two operations, everything should work, but you can be a bit more explicit about the operations involved, without the need to manually flush and close the buffers, leaving that up to the using block:

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);
        }

        byte[] buffer = memoryStream.ToArray();
        retvalue = BitConverter.ToString(buffer, 0, buffer.Length).Replace("-", "");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Please try the following in C# code.

     //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 = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length).Replace("-", "");
        //            writer.Close();
        //        }
        //        cryptoStream.Close();
        //    }
        //    memoryStream.Close();
        //}


        //return retvalue;


        ICryptoTransform ct = tdes.CreateEncryptor();
        byte[] input = Encoding.UTF8.GetBytes(toEncrypt);
        var output = ct.TransformFinalBlock(input, 0, input.Length);

        return Convert.ToBase64String(output);

We can get Base64String on the java side using the following.

          final String encodedCipherText = new sun.misc.BASE64Encoder().encode(ciphertext);
    return encodedCipherText;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.