Jump to content

help needed coverting c# des encryption to php


Paulqvz

Recommended Posts

I have never worked with des encryption before and have searched through internet getting 3 des and acb - tested multiple code but cant get encrypted the same as in c#

 

public string EncryptQueryString(string stringToEncrypt)

 

public string EncryptQueryString(string stringToEncrypt)
        {
            byte[] key = { };
            byte[] IV = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78 };
            try
            {
                key = Encoding.UTF8.GetBytes(KEY);
using (DESCryptoServiceProvider oDESCrypto = new DESCryptoServiceProvider())
                {
                    byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                    MemoryStream oMemoryStream = new MemoryStream();
                    CryptoStream oCryptoStream = new CryptoStream(oMemoryStream,
                    oDESCrypto.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                    oCryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    oCryptoStream.FlushFinalBlock();
                    return Convert.ToBase64String(oMemoryStream.ToArray());
                }
            }
            catch
            {
                throw;
            }
        }

i followed this ph example but think i am way of course

 

<?php
 
class DES
{
      protected $method;
      protected $key;
        protected $output;
        protected $iv;
     protected $options;
    const OUTPUT_NULL = '';
    const OUTPUT_BASE64 = 'base64';
    const OUTPUT_HEX = 'hex';
 
    public function __construct($key, $method = 'DES-ECB', $output = '', $iv = '', $options = OPENSSL_RAW_DATA | OPENSSL_NO_PADDING)
    {
        $this->key = $key;
        $this->method = $method;
        $this->output = $output;
        $this->iv = $iv;
        $this->options = $options;
    }
 
  
    public function encrypt($str)
    {
        $str = $this->pkcsPadding($str, 8);
        $sign = openssl_encrypt($str, $this->method, $this->key, $this->options, $this->iv);
 
        if ($this->output == self::OUTPUT_BASE64) {
            $sign = base64_encode($sign);
        } else if ($this->output == self::OUTPUT_HEX) {
            $sign = bin2hex($sign);
        }
 
        return $sign;
    }
    public function decrypt($encrypted)
    {
        if ($this->output == self::OUTPUT_BASE64) {
            $encrypted = base64_decode($encrypted);
        } else if ($this->output == self::OUTPUT_HEX) {
            $encrypted = hex2bin($encrypted);
        }
 
        $sign = @openssl_decrypt($encrypted, $this->method, $this->key, $this->options, $this->iv);
        $sign = $this->unPkcsPadding($sign);
        $sign = rtrim($sign);
        return $sign;
    }
 
    private function pkcsPadding($str, $blocksize)
    {
        $pad = $blocksize - (strlen($str) % $blocksize);
        return $str . str_repeat(chr($pad), $pad);
    }
 
 
    private function unPkcsPadding($str)
    {
        $pad = ord($str{strlen($str) - 1});
        if ($pad > strlen($str)) {
            return false;
        }
        return substr($str, 0, -1 * $pad);
    }
 
}
 
$key = 'key123456';
$iv = 'iv123456';
 

$des = new DES($key, 'DES-CBC', DES::OUTPUT_BASE64, $iv);
echo $base64Sign = $des->encrypt('Hello DES CBC');
echo "\n";
echo $des->decrypt($base64Sign);
echo "\n";
 
$des = new DES($key, 'DES-ECB', DES::OUTPUT_HEX);
echo $base64Sign = $des->encrypt('Hello DES ECB');
echo "\n";
echo $des->decrypt($base64Sign);
 

 

Edited by Paulqvz
made les cluttered
Link to comment
Share on other sites

$key = "K6u8#m2b";
$textToEncrypt = "5512065314089";
$iv = "0112233445566778";

$encrypted = openssl_encrypt($textToEncrypt, 'aes-256-cbc', $key, 0, $iv);
echo "encrypted output=" . $encrypted . "\n";
//  PART 2. DECRYPT - do the reverse
$decrypted = openssl_decrypt($encrypted,  'aes-256-cbc', $key, 0, $iv);
echo "decrypted output=" . $decrypted . "\n";
echo "expected- WfRb+Vugfc1cbJNfXKL6bw=="

 

 BASE64(IV)=MDExMjIzMzQ0NTU2Njc3OA==
encrypted output=Pt0MK+1qt0mAyU7irnWzTw==
decrypted output=5512065314089
expected- WfRb+Vugfc1cbJNfXKL6bw==

Edited by Paulqvz
more info
Link to comment
Share on other sites

With that same code I get "bimbcVvpJ/NBxllxxCsW+w==" for the encrypted output, and online sources do too. So I don't know where you're getting that Pt0MK string from, nor why you expect it to be WfRb.

Also note that your key is the wrong length: a 256-bit cipher needs a 256-bit key, and if you don't provide one long enough then it gets padded with \0s.

Link to comment
Share on other sites

2 minutes ago, Paulqvz said:

i could not give the same key as it is used in company and would be dangerous. 

So test your code with a different key. Go out into the internet and find samples encryptions to verify that your PHP code is producing the correct outputs.

 

2 minutes ago, Paulqvz said:

I also do not have c#.  All i got was this is how we do the encryption and decryption. I am litterly stuck.

This isn't just about the C# anymore. You've got AES-256 in one place, DES is another, improper PKCS padding in your PHP where the .NET code doesn't do any...

What information posted so far are you absolutely sure is correct?

Link to comment
Share on other sites

well thats why i am here - trying to understand this all. i just need des - and read somewhere to get the same as c# i should remove padding?

so please explain the pkcs padding?

 

this is the code i am now busy with. 

with the correct key on my side

 

$iv = $key;
$pass_enc = $textToEncrypt;
$block = mcrypt_get_block_size('des', 'cbc');
$pad = $block - (strlen($pass_enc) % $block);
$pass_enc .= str_repeat(chr($pad), $pad);
$pass_enc = mcrypt_encrypt(MCRYPT_DES, $key, $pass_enc, MCRYPT_MODE_CBC, $iv);
$pass_enc1 = base64_encode ($pass_enc);
echo $pass_enc1." --   ";
 

 

output

 

4Oz0+7kX3naomfZpjW7y+g== -- expected- WfRb+Vugfc1cbJNfXKL6bw==

Link to comment
Share on other sites

Okay, see, I'm going to have a really hard time explaining why your outputs are incorrect if I don't know what the inputs are. I get that you can't share your key, that's fine, but I need a key in order to verify whether something works.

I'll try from a different angle.

That C# code you posted. Is that exactly the code that was used to produce that WfRb encrypted output? If it is not the exact code, what is different?

Link to comment
Share on other sites

seriously - dumb it down a bit. relax and read the question again.

 

Key length is the same. that is the c# they have given me, and this is the php i am trying. Si in stead om rambling just none helpful links and none useful comments, rather start of by helping by explaining how to get that c# code over to des encryption with either hex or $iv = "0112233445566778"; Not being disrespectful or anything else, but if you cant help with that please do not reply again as it wastes time and space.

I have spent a whole freaking day trying to get that c# being the same as php and need real assistance

Link to comment
Share on other sites

I ran both your C# code and PHP code from your original post with the same inputs:

$key = '01234567';
$iv = "\x01\x12\x23\x34\x45\x56\x67\x78";
$value = 'param=value';

And I get the same output from each code:

C# Output:  sFi4JhEGhA4awvJPqeK0Gg==
PHP Output: sFi4JhEGhA4awvJPqeK0Gg==

So it would seem likely your issue is that you're just not using the same inputs for both codes and that's why you get different outputs.  You seem unwilling to give any details on what inputs you're using though so it's not really possible to provide you any further help until you do.   Generate a new key that you can post without worry and then show us how you're running your code and the output you're getting.

 

Edited by kicken
Link to comment
Share on other sites

4 hours ago, Paulqvz said:

seriously - dumb it down a bit. relax and read the question again.

I've tried dumbing it down. It hasn't worked so far.

 

4 hours ago, Paulqvz said:

Key length is the same.

I don't care that it's "the same" (nor even know what it's "the same" as). I want to know how many bytes are in your key. Or bits. Same thing. Because if the number is anything other than the number I expect, that will influence how the encryption and decryption process works.

So I'll ask again: how many bytes/bits are in your key?

 

4 hours ago, Paulqvz said:

that is the c# they have given me,

Then you have a problem because the code they gave you doesn't include a key.

It also includes an IV, which is not used for (what I believe to be) .NET's default behavior of CBC mode, so either the IV is irrelevant or .NET is switching to EBC mode based on the presence of an IV.
But that doesn't really matter much because it's only two possibilities to try out: with the right key, one of those two modes in PHP should produce the same output.

 

4 hours ago, Paulqvz said:

I have spent a whole freaking day trying to get that c# being the same as php and need real assistance

Give me some real answers and we can make progress.

I'll ask an earlier question again to echo what kicken said: create for yourself a new key that you can test with, then post it here so that we can all be on the same page.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.