Leong
Leong

Reputation: 139

3DES encryption from c# to php

I need php 3DES encryption to generate timestamp to connect to a web service

I want to generate timestamp in php, I have the C# sample code. But my php code generates differently from the source code.

Here is my php code

class trytry{


    public function encrypt2($data, $secret)
    {
        //Generate a key from a hash
        $key = md5(utf8_encode($secret), true);

        //Take first 8 bytes of $key and append them to the end of $key.
        $key .= substr($key, 0, 8);

        //Pad for PKCS7
        $blockSize = mcrypt_get_block_size('tripledes', 'ecb');
        $len = strlen($data);
        $pad = $blockSize - ($len % $blockSize);
        $data .= str_repeat(chr($pad), $pad);

        //Encrypt data
        $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');

        return base64_encode($encData);
    }

    public function decrypt2($data, $secret)
    {
        //Generate a key from a hash
        $key = md5(utf8_encode($secret), true);

        //Take first 8 bytes of $key and append them to the end of $key.
        $key .= substr($key, 0, 8);

        $data = base64_decode($data);

        $data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');

        $block = mcrypt_get_block_size('tripledes', 'ecb');
        $len = strlen($data);
        $pad = ord($data[$len-1]);

        return substr($data, 0, strlen($data) - $pad);
    }

    public function return_timestap(){

        date_default_timezone_set('GMT');
        return $date = date('D, d M Y H:i:s')." GMT" ;

        //." GMT" 
       // this is code to generate 
    }

}

C# sample code

using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace MemberSite.OddsDisplay.Helpers
{
    public class DES3
    {
        private byte[] bKey;
        private byte[] bIV;
        private SymmetricAlgorithm mCSP = new AesCryptoServiceProvider();

        public DES3(byte[] key)
        {
            bKey = key;
        }
        public DES3(byte[] key, byte[] iv)
        {
            bKey = key;
            bIV = iv;
        }
    }

    public string EncryptString(string Value)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = bKey;
            mCSP.IV = bIV;
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
            byt = Encoding.UTF8.GetBytes(Value);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }

    public string DecryptString(string Value)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = bKey;
            mCSP.IV = bIV;
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
            byt = Convert.FromBase64String(Value);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        }

    public class Hash
    {
        public static string StringMD5(string data)
        {
            return (
                System.BitConverter.ToString(
                    System.Security.Cryptography.MD5.Create().ComputeHash(
                        System.Text.Encoding.UTF8.GetBytes(data)
                    )
                )
            );
        }
        public static byte[] BytesMD5(string data)
        {
            return (
                System.Security.Cryptography.MD5.Create().ComputeHash(
                    System.Text.Encoding.UTF8.GetBytes(data)
                )
            );
        }
    }
}



public string GetTimeStamp(string accessKey, string ivKey)
    {
        string timeStamp = string.Empty;

        byte[] key = Hash.BytesMD5(accessKey);
        byte[] ivbyte = Hash.BytesMD5(ivKey);
        DES3 des3 = new DES3(key, ivbyte);
        timeStamp = des3.EncryptString(getTimestampString(DateTime.Now));

        return timeStamp;
    }

Timestamp data: Thu, 06 Jun 2019 09:38:03 GMT

Result PHP

QMaMk7ipbL73QLy6tbGBBG6vWJPBqsTEUt2mIpjKhjc=

Result C#

CKdZRaEoT0UgH9KVbc5Oyc1WXspLu/uoIGqCxxnavXc=

Can anyone explain and point out why my code is not working ?

Any help will be highly appreciated

Thanks in advance

Upvotes: 1

Views: 371

Answers (1)

Firstly, your PHP uses tripledes but C# uses AES

Secondly, key in your C# code and PHP are not equal

In php you have

    //Generate a key from a hash
    $key = md5(utf8_encode($secret), true);

    //Take first 8 bytes of $key and append them to the end of $key.
    $key .= substr($key, 0, 8);

You append 8 bytes to key to make it becomes 24 bytes key length

But in C#

    byte[] key = Hash.BytesMD5(accessKey);

This is 16 bytes key length.

Because your requirement is have PHP encrypt and decrypt the same like C#, so I focus to change your php code only

    public function encrypt2($data, $secret)
    {
        //Generate a key from a hash
        $key = md5(utf8_encode($secret), true);

        // Remove this
        //Take first 8 bytes of $key and append them to the end of $key.
        //$key .= substr($key, 0, 8);

        //Pad for PKCS7
        $blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $len = strlen($data);
        $pad = $blockSize - ($len % $blockSize);
        $data .= str_repeat(chr($pad), $pad);

        //Encrypt data MCRYPT_RIJNDAEL_128, ECB equal to C# AES
        $encData = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB);

        return base64_encode($encData);
    }

    function decrypt2($data, $secret)
    {
        //Generate a key from a hash
        $key = md5(utf8_encode($secret), true);

        // Remove this
        //Take first 8 bytes of $key and append them to the end of $key.
        //$key .= substr($key, 0, 8);

        $data = base64_decode($data);

        $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB);

        $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $len = strlen($data);
        $pad = ord($data[$len-1]);

        return substr($data, 0, strlen($data) - $pad);
    }

Upvotes: 1

Related Questions