MACTripleDES in PHP
Asked Answered
M

2

6

I am trying to get a MAC TripleDES equivalent of the C# MACTripleDES class.

I have tried following mcrypt(), but that is just encoding in TripleDES. I need to get an equivalent MACTripleDES string as the one that is generated in C# to authenticate a message.

I have also looked at PHP's hash_hmac() function but it does not give the option of generating a MAC with TripleDES

Maloriemalory answered 10/5, 2012 at 12:5 Comment(0)
C
7

I'm not sure since Microsoft didn't bother to say what standard their class conforms to, but I suspect that this NIST document is what the Microsoft class is computing, only using triple DES in place of DES.

I guess you will have to write your own method using the primitives in mcrypt.

EDIT 1:

Inspired by the bounty, I have these two examples showing equivalent result in PHP and C#.

First, C#:

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

namespace TDESMacExample
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            var keyString = "012345678901234567890123";
            var keyBytes = Encoding.ASCII.GetBytes(keyString);
            var mac = new MACTripleDES(keyBytes);
            var data = "please authenticate me example number one oh one point seven niner";
            Console.WriteLine(data.Length);
            var macResult = mac.ComputeHash(Encoding.ASCII.GetBytes(data));
            Console.WriteLine(BitConverter.ToString(macResult));
            // B1-29-14-74-EA-E2-74-2D
        }
    }
}

Next, PHP:

    <?php
    $data = 'please authenticate me example number one oh one point seven niner';
    $key = '012345678901234567890123'; // Key must be 24 bytes long
    $iv = '\x00\x00\x00\x00\x00\x00\x00\x00'; // All zero IV is required

    $cipher = mcrypt_cbc(MCRYPT_3DES, $key, $data, MCRYPT_ENCRYPT, $iv);
    $mac_result = substr($cipher, -8); // Last 8 bytes of the cipher are the MAC

    echo "mac result : " . bin2hex($mac_result);
    echo "<br>";
    ?>
Cryptomeria answered 10/5, 2012 at 22:50 Comment(3)
Sorry for the delay - I managed to get the code done and it's the same way you have done.Maloriemalory
Dear GregS, is there any C# code example that shows how to decrypt this encrypted string? ThanksPortraiture
@MichaelSamteladze: You don't decrypt a MAC because it isn't encryption. It's a hash function with a key. It's used as a kind of checksum.Cryptomeria
D
1

The MAC is simply the last eight bytes of the CBC encrypted data. If the key, IV, and the padding method matches, you should be able to just use those bytes.

For more details about MAC definition, see Appendix F of FIPS-81, DES Modes of Operation.

Dessiatine answered 16/5, 2012 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.