How to convert C# code to create an auth key into PHP
Get the solution ↓↓↓I have code to generate an auth key in C# that looks like:
public string generateToken()
{
byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());
return token;
}
An auth key looks like this:21VMky3f10ik7t5IeGKCSrA+MO10rN2N
And code to decode it that looks like this:
public bool decodeToken(string token)
{
byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24))
{
//token is more than 24 hours old
return false;
} else
{
return true;
}
}
How would I translate thedecodeToken
function into a PHP function so I can verify the token on a server.
My current PHP code is as follows:
$decoded = base64_decode($token);
$rawBytes = "";
foreach(str_split($decoded) as $byte)
{
$rawBytes .= ' ' . sprintf("%08b", ord($byte));
}
$new = unpack("q",$rawBytes);
$time = ticks_to_time($new[1]);
return date("F j Y g:i:s A T", $time);
$new[1] =3544386994072269088
which is then turned into a datetime giving:
September 18 11232 6:16:47 PM UTC
This is not correct and I don't know how to fix it
Thanks!
Answer
Solution:
The Int64 value can be determined directly after the base64_decode with unpack. int64 is a 64-bit signed integer that encodes the Kind property into a 2-bit field and the Ticks property into a 62-bit field. The ticks must be filtered out using a mask. The ticks are then converted into the linux timestamp.
$token = "21VMky3f10ik7t5IeGKCSrA+MO10rN2N";
$decoded = base64_decode($token);
$decArr = unpack("q",$decoded);
$int64 = $decArr[1]; //5248909277561378267 = 2 bit kind and 62 bit ticks
$ticks = ($int64 & 0x3fffffffffffffff);
$linuxTs = $ticks/10000000 - 62135596800;
echo gmdate("Y-m-d H:i:s",$linuxTs);
//2020-04-12 22:05:13
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.