Question

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

Was it helpful?

Solution

TripleDES has a 64-bit block size. You need to use an 8 byte IV in C#.

OTHER TIPS

Got the answer. decodeBase64 method from apache common framework (commons.codec.binary.Base64) does the necessary. Thanks mfanto for the heads up.!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top