2009-04-22 121 views
1

C#2005 我正在使用簡單的加密和解密IP地址。遠程服務器上的應用程序將加密IP地址,客戶端將對其解密。但是,當客戶端解密IP時,我只能得到一些IP地址。剩下的就是垃圾。 前:123.456.78.98 後:fheh &^G.78.98c#加密和解密

非常感謝,

/// Encrypt the SIP IP address in the remote server 
     private void encryptSIP_IP(string sip_ip) 
     { 
      TripleDESCryptoServiceProvider encrypt = new TripleDESCryptoServiceProvider(); 

     /// Private key 
     byte[] key = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0}; 

     encrypt.Key = key; 
     byte[] byteSIP = System.Text.Encoding.Default.GetBytes(sip_ip); 

      ICryptoTransform encryptor = encrypt.CreateEncryptor(); 
      byte[] encrypted_sip = encryptor.TransformFinalBlock(byteSIP, 0, byteSIP.Length); 



/// This will decrypt in the client application 
     private void decryptSIP_IP(byte[] encrypted_sip) 
     { 
      TripleDESCryptoServiceProvider decrypt = new TripleDESCryptoServiceProvider(); 
      /// Private key 
      byte[] key = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0 }; 
      decrypt.Key = key; 
      ICryptoTransform decryptor = decrypt.CreateDecryptor(); 

      byte[] original = decryptor.TransformFinalBlock(encrypted_sip, 0, encrypted_sip.Length); 
      string ip = System.Text.Encoding.Default.GetString(original); 
     } 
     } 

回答

8

隨着一鍵,你需要一個Initialization Vector(8個字節爲您的情況):

// To Encrypt 
encrypt.IV = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; 

// Use same IV to decrypt 
decrypt.IV = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; 
1

你試過雙方明確設置編碼?也許默認是不同的。

2

正如達林已經說了,你需要設置初始化向量。如果可能的話,爲每個加密過程選擇一個隨機的,並以明文形式傳輸/保存。

順便說一句,你應該看看CryptoStream,而不是使用TransformBlock/TransformFinalBlock ......它更清潔,恕我直言。

+0

那是怎麼回事?你能解釋一下嗎? (使用流) – 2011-05-05 09:47:13