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";Leave a comment