1

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

3 Answers 3

8

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 };
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

How is that? Could you explain? (usage of stream)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.