3v4l.org

run code in 300+ PHP versions simultaneously
<?php function _xor($text,$key){ $outText = ''; for($i=0;$i<strlen($text);) { for($j=0;($j<strlen($key) && $i<strlen($text));$j++,$i++) { $outText .= $text{$i} ^ $key{$j}; } } return $outText; } $encoding_key = 'c422fdd0d81f'; // Encoding key and integrity key will $integrity_key = 'fe3fd7dd8731'; // be exchanged between you and Improve Digital $algo = 'sha1'; // HMAC algorithm used $price = 300; // Price to be encrypted. Up to 8 Bytes, treated as string // 1. Create a (hopefully) unique 16-byte initialization string: // This is an example and can be replaced by something faster if needed $initialization_vector = substr(hash("sha256", microtime(TRUE).rand(0,9999).time()),0,16); // 2. Encrypt the price: // The encrypted price is the result of a bitwise XOR (^) of the price and a HMAC-Hash of // the initialization string and the encoding key. Since xor does not bloat or shrink the // encrypted string, we are already changing the input to 8 bytes. // // Common pitfalls: // - Price to be encrypted MUST be a string. It will most likely behave unexpected if // treated as float // - Hash has to be RAW output (TRUE Parameter). If missed out, lowercase hexits will be // used and cause decryption to fail. $encrypted_price = _xor( substr(number_format($price,8),0,8), hash_hmac($algo, $initialization_vector,$encoding_key, TRUE )); // 3. Create the integrity // Another hash to be created to allow verification of the decrypted price. Integrity // key instead of encryption key is used // Only the first 4 Bytes are being used so the rest is omitted immediately. $integrity = substr(hash_hmac($algo, substr(number_format($price,8),0,8).$initialization_vector, $integrity_key, TRUE),0,4); // 4. Glue the parts togetger // 16 byte initialization string + 8 bytes encrypted price + 4 bytes of integrity will be // base64-encoded $out = base64_encode($initialization_vector.$encrypted_price.$integrity); // 5. Replace / with . and + with - to make the encoded string URL-safe. $urlsafe = str_replace('/','.',str_replace('+', '-', $out)); echo $urlsafe; // Done

preferences:
35.96 ms | 402 KiB | 5 Q