2013-01-16 11 views
0

在我們的應用程序中,我們使用三重DES來加密和解密數據。我們在C#中使用24字節密鑰和12字節IV的enc/dec代碼,這很好地工作。現在我們想要在java中實現相同的代碼,但是當我使用12字節IV時,在java中出現錯誤,表示錯誤的IV大小。當我搜索時,我知道java使用8字節IV。現在我很困惑,C#和JAVA在三重DES方面的實現差異如何。或者我錯過了什麼?在C#和Java中實現三重DES有什麼區別嗎? Java給錯誤錯誤的IV大小

這類似於我們的加密代碼

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

回答

2

TripleDes的有64-bit block size。您需要在C#中使用8 byte IV

+0

我已經添加了有問題的代碼。 'Convert.FromBase64String'將字符串轉換爲8字節數組嗎? – Tejas

+0

是的。只是檢查它。 IV中的C#是8個字節。我怎樣才能在JAVA中實現相同? – Tejas

+0

對不起,你的問題是什麼?如果我的回答回答了您的問題,您是否可以註冊並將其標記爲已接受? – mfanto

0

得到了答案。 decodeBase64方法從apache通用框架(commons.codec.binary.Base64)做必要的。 感謝mfanto的領導。