tags:

views:

725

answers:

3

Hello,

C# 2005 I am using a simple encrypt and descrypt for a IP address. The app on the remote server will encrypt the ip address and the client will decrypt it. However, when the client descrypts the IP I only get some of the IP address back. The rest is rubbish. Before: 123.456.78.98 After: fheh&^G.78.98

Many thanks,

 /// 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);
        }
        }
+1  A: 

Have you tried setting the encoding explicitly on both sides? Maybe the default is different.

Sandor Davidhazi
+8  A: 

Along with a key you need an Initialization Vector (8 bytes for your case):

// 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 };
Darin Dimitrov
+2  A: 

As darin already said, you need to set the Initialization Vector. If possible, choose a random one for each encryption process and transfer/save it in clear text.

By the way, you should look into CryptoStream instead of working with TransformBlock/TransformFinalBlock ... it's much cleaner, imho.

Jabe