Home > Back-end >  Binary Conversion Results In 00000000000
Binary Conversion Results In 00000000000

Time:12-30

I'm testing some of my code that generates a passcode:

<?php
//8076?
$key = '8076e852267ecefe2a80c76b66ba8ca99fb7874fa5556e8b64f4707003f4aed0';

$a = time() . $key;
print "a = $a" . PHP_EOL;
$b = sprintf('%b', $a);                            
print "b = $b" . PHP_EOL;
$totp = hash('sha3-256', $b);
print "totp = $totp" . PHP_EOL;

$x = gmp_init(0);
$y = gmp_init(1);
for ($i = strlen($totp) - 1; $i >= 0; $i--, $y = gmp_mul($y, 16))
  $x = gmp_add($x, gmp_mul($y, hexdec($totp[$i])));
print "x = $x" . PHP_EOL;

print sprintf('d', gmp_strval(gmp_mod($x, '100000000')));
print PHP_EOL;

The results are:

a = 16407820138076e852267ecefe2a80c76b66ba8ca99fb7874fa5556e8b64f4707003f4aed0
b = 0
totp = f9e2eaaa42d9fe9e558a9b8ef1bf366f190aacaa83bad2641ee106e9041096e4
x = 113026826332749616999480801584179790214435636530758034338031008093509348529892
48529892

Why is b = 000000...?

I need to have a different passcode every time this key is used to generate it. I know this is stupid, a random number would work and be just as "secure". Security people are making me do this. I'm a software engineer.

There is something weird about this hex number. I get a good result for other values. For example $key = '3a8b9846009b54bb7a11e900e9b50000a6e14da4c4c2ef49f4016c326c339694' works fine.

CodePudding user response:

You're formatting the string $a as a binary number which doesn't make sense, you want to convert it. You need to use pack and then convert that binary value to a string or integer or leave it as is, whatever you need.

CodePudding user response:

This works now. (The hex string does not contain valid hex values so I used each character)


<?php

//$key = '8076e852267ecefe2a80c76b66ba8ca99fb7874fa5556e8b64f4707003f4aed0';
//$key = '3a8b9846009b54bb7a11e900e9b50000a6e14da4c4c2ef49f4016c326c339694';
$key = '145bfea3b819bee905b5d5295338964150c489789a9228f2e981b189de5cbbee';

$a = '';
for ($i = 0; $i < strlen($key); $i  )
   $a .= decbin(ord($key[$i]));
$a .= decbin(time());
print "a = $a" . PHP_EOL;
$totp = hash('sha3-256', $a);
print "totp = $totp" . PHP_EOL;

$x = gmp_init(0);
$y = gmp_init(1);
for ($i = strlen($totp) - 1; $i >= 0; $i--, $y = gmp_mul($y, 16))
  $x = gmp_add($x, gmp_mul($y, hexdec($totp[$i])));
print "x = $x" . PHP_EOL;

print sprintf('d', gmp_strval(gmp_mod($x, '100000000')));
print PHP_EOL;

CodePudding user response:

I think 8076 at the beginning is messing it up?

  • Related