Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .NET and PHP encryption

I have the following c# code that generates keys:

    public static byte[] Encrypt(byte[] plainData, string salt)
    {
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        DES.Key = ASCIIEncoding.ASCII.GetBytes(salt);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(salt);
        ICryptoTransform desencrypt = DES.CreateEncryptor();
        byte[] encryptedData = desencrypt.TransformFinalBlock(plainData, 0, plainData.Length);
        return encryptedData;
    }

    private string GetEncryptedKey(string key)
    {
        return BitConverter.ToString(KeyGeneratorForm.Encrypt(ASCIIEncoding.ASCII.GetBytes(key), "abcdefgh")).Replace("-", "");
    }

I'm trying to perform the same thing in PHP:

function get_encrypted_key($key){
    $salt = "abcdefgh";
    return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt));
}

However, there is a small discrepency in the results, as the last 16 chars are always different:

With key "Benjamin Franklin":
C# : 0B3C6E5DF5D747FB3C50DE952FECE3999768F35B890BC391
PHP: 0B3C6E5DF5D747FB3C50DE952FECE3993A881F9AF348C64D

With key "President Franklin D Roosevelt":
C# : C119B50A5A7F8C905A86A43F5694B4D7DD1E8D0577F1CEB32A86FABCEA5711E1
PHP: C119B50A5A7F8C905A86A43F5694B4D7DD1E8D0577F1CEB37ACBE60BB1D21F3F

I've also tried to perform the padding transform to my key using the following code:

function get_encrypted_key($key){
    $salt = "abcdefgh";

    $extra = 8 - (strlen($key) % 8);
    if($extra > 0) {
        for($i = 0; $i < $extra; $i++) {
            $key.= "\0";
        }
    }

    return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt));
}

But I end up with the same results as without padding.

If you have any clue as to what's going on, I'd be glad to hear about it! :)

Thanks

like image 265
koni Avatar asked Jun 12 '12 20:06

koni


1 Answers

You mentioned trying a "classic" padding snippet. The following quick adaptation of the snippet posted on the mcrypt_encrypt documentation gives the same results you were getting from C#.

PKCS #7 (the default padding scheme used by C#'s SymmetricAlgorithm) pads with bytes where each padding byte's value is the same as the number of bytes of padding, not with zero bytes.

function get_encrypted_key($key)
{
    $salt = 'abcdefgh';
    $block = mcrypt_get_block_size('des', 'cbc');
    $pad = $block - (strlen($key) % $block);
    $key .= str_repeat(chr($pad), $pad);

    return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt));
}

Test output:

php > echo get_encrypted_key('Benjamin Franklin');
0b3c6e5df5d747fb3c50de952fece3999768f35b890bc391
php > echo get_encrypted_key('President Franklin D Roosevelt');
c119b50a5a7f8c905a86a43f5694b4d7dd1e8d0577f1ceb32a86fabcea5711e1
like image 98
John Flatness Avatar answered Nov 18 '22 06:11

John Flatness