The expanses of WolfWings' land
scratched on the wall for all to see


July 18th, 2008
July 18th, 2008
July 18th, 2008
July 18th, 2008
July 18th, 2008

[User Picture]11:48 am - For anyone working with HMAC logins...
Okay... I'm usually running WAMP2 at work to test my *AMP-based website I'm working on, and have been working to build a best-practices non-HTTPS login system. That means using HMAC.</p>

The JavaScript side is a no-brainer, Paj has the source code for an understandable toolkit.

The PHP side is also, relatively, a no-brainer. You either use the mhash() function from the Mhash extension or you can use the exploded version that only relies on the built-in sha1() function if the Mhash extension isn't available for whatever reason.

Well... I decided to implement mine as a stored function in MySQL, because I like the idea of the PHP-known MySQL account being unable to call any SQL commands directly, only black-box functions with strongly typed inputs and outputs. I'm not holding credit-cards or anything in the database, but I'd rather not open up any attack vectors I don't need to, and preventing anything but calling functions the same way the website forms intend them to be called seems like a very good, albeit sledgehammer-ish, approach.

So, the code.

DROP FUNCTION IF EXISTS hex_hmac_sha1;
DELIMITER |
CREATE FUNCTION hex_hmac_sha1(k VARCHAR(1000), d VARCHAR(1000))
  RETURNS VARCHAR(1000) DETERMINISTIC
  BEGIN
    DECLARE ipad CHAR(64);
    DECLARE opad CHAR(64);
    DECLARE i INT;
    SET k = IF(LENGTH(k)>64,UNHEX(SHA1(k)),k);
    SET k = RPAD(k,64,CHAR(0));
    SET i = 0, ipad = "", opad = "";
    REPEAT
     SET i = i + 1;
     SET ipad = CONCAT(ipad, CHAR(ASCII(MID(k,i,1)) ^ 54)),
         opad = CONCAT(opad, CHAR(ASCII(MID(k,i,1)) ^ 92));
    UNTIL i >= 64 END REPEAT;
    RETURN SHA1(CONCAT(opad,UNHEX(SHA1(CONCAT(ipad, d)))));
  END|
DELIMITER ;
SELECT hex_hmac_sha1("Jefe","what do ya want for nothing?");
SELECT "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79";

1 commentLeave a comment
?

Log in

No account? Create an account