A Java mac check domain algorithm, which expert can help rewrite it into a PHP version.
Message format: Domain 0|Domain 1|Domain 2|……|Domain n
Domain n is the MAC verification domain
public static byte[] getMac(byte[] dt, int mlen) {
int n, k, len, ilen;
// original input String length
len = dt.length;
// 原始串和mac长度的余数
k = len % mlen;
//
n = mlen - k;
ilen = len + n;
byte[] bt = new byte[ilen];
for (int i = 0; i < len; i++) {
dt[i] = (byte) (dt[i] > 0x00 ? dt[i] : dt[i] + 256);
bt[i] = dt[i];
}
bt[len] = 127;
byte bo[] = new byte[mlen];
for (int i = 0; i < ilen;) {
for (int j = 0; j < mlen; j++) {
bo[j] ^= bt[i];
i++;
}
}
for (int i = 0; i < mlen; i++) {
// 如果遇到\r \n
if ((bo[i] >= 0x00 ? bo[i] : bo[i] + 256) >= 0x80) { // "\r"
bo[i] ^= 0x80;
}
if (bo[i] == 0x0d) { // "\r"
bo[i] = 0x4d;
}
if (bo[i] == 0x0a) { // "\n"
bo[i] = 0x4a;
}
if (bo[i] == 0x3a) { // ":"
bo[i] = 0x7a;
}
if (bo[i] == 0x7c) { // "|"
bo[i] = 0x3c;
}
if (bo[i] == 0x00) { // "0"
bo[i] = 0x40;
}
}
return bo;
}
PHP中文网2017-06-26 10:51:17
public static function getMac($dt, $mlen) {
int $n, $k, $len, $ilen;
// original input String length
$len = array_length($dt);
// 原始串和mac长度的余数
$k = $len % $mlen;
//
$n = $mlen - $k;
$ilen = $len + $n;
$bt = [];
for (int $i = 0; $i < $len; $i++) {
$dt[$i] = $dt[$i] > 0x00 ? $dt[$i] : $dt[$i] + 256;
$bt[$i] = $dt[$i];
}
$bt[$len] = 127;
$bo = [];
for ($i = 0; $i < $ilen;) {
for ($j = 0; $j < $mlen; $j++) {
$bo[$j] ^= $bt[$i];
$i++;
}
}
for ($i = 0; $i < $mlen; $i++) {
// 如果遇到\r \n
if (($bo[$i] >= 0x00 ? $bo[$i] : $bo[$i] + 256) >= 0x80) { // "\r"
$bo[$i] ^= 0x80;
}
if ($bo[$i] == 0x0d) { // "\r"
$bo[$i] = 0x4d;
}
if ($bo[$i] == 0x0a) { // "\n"
$bo[$i] = 0x4a;
}
if ($bo[$i] == 0x3a) { // ":"
$bo[$i] = 0x7a;
}
if ($bo[$i] == 0x7c) { // "|"
$bo[$i] = 0x3c;
}
if ($bo[$i] == 0x00) { // "0"
$bo[$i] = 0x40;
}
}
return $bo;
}
以上是直接翻译,以下是写得更好得:
public static function getMac($dt, $mlen) {
int $n, $k, $len, $ilen;
// original input String length
$len = array_length($dt);
// 原始串和mac长度的余数
$k = $len % $mlen;
//
$n = $mlen - $k;
$ilen = $len + $n;
$bt = [];
$bt[$len] = 127;
foreach($dt as $key => &$value) {
$value = $value > 0x00 ? $value : $value + 256;
$bt[$i] = $value;
}
unset($value);
$bo = [];
foreach($bt as $value) {
for($j = 0; $j < $mlen; $j++) {
$bo[$j] ^= $value;
}
}
unset($value);
foreach($bo as &$value) {
// 如果遇到\r \n
if (($value >= 0x00 ? $value : $value + 256) >= 0x80) { // "\r"
$value ^= 0x80;
}
switch($value) {
case 0x0d:// "\r"
$value = 0x4d;
break;
case 0x0a:// "\n"
$value = 0x4a;
break;
case 0x3a:// ":"
$value = 0x7a;
break;
case 0x7c:// "|"
$value = 0x3c;
break;
case 0x00:// "0"
$value = 0x40;
break;
}
}
return $bo;
}