問題描述
我們正在嘗試實現一個函數 P_SHA1 表示 PHP.用 Python 編寫的函數的模式.但是,不幸的是,有些東西不能正常工作.下面是JAVA中的實現函數:http://ws.apache.org/wss4j/xref/org/apache/ws/security/conversation/dkalgo/P_SHA1.html
we are trying to implement a function P_SHA1 means PHP. The pattern of the function written in Python. But, unfortunately, something is not working properly. Here is the implementation function in JAVA: http://ws.apache.org/wss4j/xref/org/apache/ws/security/conversation/dkalgo/P_SHA1.html
我們的代碼:
<?php
$newSeed = $label . $seed; // concat as strings
// $p_sha1
$psha1 = p_hash('sha1', $secret, $newSeed, $length);
$string = arrayToBytes($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 call_user_func_array("pack", array_merge(array("C*"), $array)); }
?>
也許有人知道我在哪里可以找到現成的解決方案?或者任何人都可以幫助編寫腳本以使其正常工作?
Maybe someone knows where I can find a ready-made solution? Or anyone can help make a script to work properly?
推薦答案
這是基于 回復通過簽名 FS" SOAP 消息請求.我已經成功地使用它來簽署 SOAP 請求并獲得我想要的響應.
This is based on the C# method included in a reply to "signing SOAP message request via ADFS". I have successfully used it to sign SOAP requests and get the response I want.
function psha1($clientSecret, $serverSecret, $sizeBits = 256)
{
$sizeBytes = $sizeBits / 8;
$hmacKey = $clientSecret;
$hashSize = 160; // HMAC_SHA1 length is always 160
$bufferSize = $hashSize / 8 + strlen($serverSecret);
$i = 0;
$b1 = $serverSecret;
$b2 = "";
$temp = null;
$psha = array();
while ($i < $sizeBytes) {
$b1 = hash_hmac('SHA1', $b1, $hmacKey, true);
$b2 = $b1 . $serverSecret;
$temp = hash_hmac('SHA1', $b2, $hmacKey, true);
for ($j = 0; $j < strlen($temp); $j++) {
if ($i < $sizeBytes) {
$psha[$i] = $temp[$j];
$i++;
} else {
break;
}
}
}
return implode("", $psha);
}
需要注意的重要一點是,客戶端機密和服務器機密在傳遞給此函數之前應該進行 base64 解碼.
One thing of importance to note is that the client secret and server secret should be base64 decoded before being passed to this function.
這篇關于PHP中P_SHA1算法的實現的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!