Skip to content

Instantly share code, notes, and snippets.

@lotas
Created October 24, 2013 21:51
Show Gist options
  • Save lotas/7145686 to your computer and use it in GitHub Desktop.
Save lotas/7145686 to your computer and use it in GitHub Desktop.
p-sha1 in php
<?php
$secret = base64_decode('kAIthWJeZ3UoS4k6qLIbfA==');
$label = base64_decode('L3JLyhzv0VTomcnzcDjoAhaMNCk=');
$seed = base64_decode('yP9lu4OUF1ah534Re/ZfcQ==');
$newSeed = $label . $seed; // concat as strings
$length = 16;
// $p_sha1
$psha1 = p_hash('sha1', $secret, $newSeed, $length);
var_dump(implode(', ', $psha1));
/**
* P_SHA1 crypto alg calculation
*
* @return array of bytes - key
**/
function p_hash($algo, $secret, $seed, $length)
{
$bytes = array_fill(0, $length, 0);
$tmp = null;
$A = $seed;
$index = 0;
while (1) {
// hmac sha1: secret + seed
$A = hash_hmac($algo, $secret, $A, true);
// hmac sha1: secret + 1st hash + seed
$output = hash_hmac($algo, $secret, ($A . $seed), true);
foreach (bytesToArray($output) as $c) {
if ($index >= $length) {
return $bytes;
}
$bytes[$index] = $c;
$index++;
}
}
return $bytes;
}
function bytesToArray($bytes) { return unpack('C*', $bytes); }
function arrayToBytes($array) { return pack('C*', $array); }
/*
p_sha1 = P_hash(sha, S2, concatArrays(stringToBytes(label), seed), length)
+def P_hash(hashModule, secret, seed, length):
+ bytes = createByteArrayZeros(length)
+ secret = bytesToString(secret)
+ seed = bytesToString(seed)
+ A = seed
+ index = 0
+ while 1:
+ A = hmac.HMAC(secret, A, hashModule).digest()
+ output = hmac.HMAC(secret, A+seed, hashModule).digest()
+ for c in output:
+ if index >= length:
+ return bytes
+ bytes[index] = ord(c)
+ index += 1
+ return bytes
*/
@AAlvarez90
Copy link

Hi, has this code been tested in a WS-security complaint web service?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment