1 Reply Latest reply: Oct 13, 2013 8:30 AM by Yuriy Belenko RSS

    Flex 4.0 HMAC.hash binary data

    richardchristie Community Member

      I am trying to replicate a function I have in php, in my flex code:

       

      If PHP:

      $mac = base64_encode(hash_hmac('sha256', $message, $secret, true));

      If the last element is a true the hash_hmac is outputted as raw binary data, if it is false outputs lowercase hexits.

       

      I have the following code written in Flex:

      encryptedString = HMAC.hash(tempString,message,algorithm); 

       

      In flex I am using the following imports:

       

           import com.adobe.crypto.HMAC;

           import com.adobe.crypto.SHA256;

       

       

      However, it outputs it as lowercase hexit. I can not find out how to convert the Flex output to binary data to match the PHP.

       

      Does anyone know?

        • 1. Re: Flex 4.0 HMAC.hash binary data
          Yuriy Belenko

          I've solved this problem by adding self-made function in HMAC Class:

           

          /**
          * Performs the HMAC hash algorithm using string.
          * This function equals php "hash_hmac" function when "raw_output" parameter is set to true.
          * @param secret The secret key
          * @param message The message to hash
          * @param algorithm Hash object to use
          * @return raw binary data as ByteArray
          */
          public static function getRawHash(secret:String, message:String, algorithm:Object = null):ByteArray {
                    var hexHash:String = hash(secret, message, algorithm); 
                    var hashBinary:ByteArray = new ByteArray();
          
                    for (var i:uint = 0; i < hexHash.length; i += 2) {
                         var c:String = hexHash.charAt(i) + hexHash.charAt(i + 1);
                         hashBinary.writeByte(parseInt(c, 16));
                    }
                    return hashBinary; 
          }
          

           

          After, if you neen "base64" string you can do something like that:

           

          private function createHashForSign(secretKey:String, message:String):String {
                    var hash:ByteArray = HMAC.getRawHash(secretKey, message, SHA1); 
                    var baseEncoder:Base64Encoder = new Base64Encoder();
                    baseEncoder.encodeBytes(hash, 0, hash.length); 
                    return baseEncoder.toString(); 
          }