Есть ли разница между реализацией Triple DES в C# и Java? Java выдает ошибку неправильного размера IV

В нашем приложении мы используем Triple DES для шифрования и дешифрования данных. У нас есть код enc/dec на C#, который использует 24-байтовый ключ и 12-байтовый IV, который отлично работает. Теперь мы хотим реализовать тот же код в java, но когда я использую 12-байтовый IV, я получаю сообщение об ошибке в java, говорящее о неправильном размере IV. Когда я погуглил, я узнал, что java использует 8-байтовый IV. Теперь я в замешательстве, почему существует разница в реализации C # и JAVA для тройного DES. Или я что-то упускаю?

Это что-то похожее на наш код шифрования

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

}

Вот как мы его используем:

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


person Tejas    schedule 16.01.2013    source источник


Ответы (2)


TripleDES имеет 64-битный размер блока. Вам нужно использовать 8-байтовый IV в C#.

person mfanto    schedule 16.01.2013
comment
Я добавил рассматриваемый код. Преобразует ли «Convert.FromBase64String» строку в 8-байтовый массив? - person Tejas; 16.01.2013
comment
Ага. только что проверил. IV в С# имеет размер 8 байт. Как я могу добиться того же в JAVA? - person Tejas; 16.01.2013
comment
Извините, какой у вас вопрос? Если мой ответ ответил на ваш вопрос, можете ли вы проголосовать и отметить его как принятый? - person mfanto; 16.01.2013
comment
На самом деле ваш ответ описал проблему. :) - person Tejas; 16.01.2013

Получил ответ. Метод decodeBase64 из общей структуры apache (commons.codec.binary.Base64) делает все необходимое. Спасибо, mfanto, за наводку!

person Tejas    schedule 16.01.2013