Convert python uuid hashing code to php - php

I'm trying to port large chunk of python code to php - while doing so I've found this one line which I can't find equivalent for:
instance = resp.get(
'instance',
uuid.uuid4().hex.encode('utf-8')
)
sha = hashlib.sha1(
self.username.encode('utf-8') + instance
)
self.params.update({'id': sha.hexdigest().upper()})
I've found https://github.com/ramsey/uuid to generate uuid4 and tried to mimic above like so:
if (isset($resp['instance']))
{
$instance = $resp['instance'];
}
else
{
$uuid4 = Uuid::uuid4();
$instance = utf8_encode(dechex($uuid4->toString()));
}
$sha = sha1(utf8_encode($this->username) . $instance);
$this->params['id'] = strtoupper($sha);
This does not seem to provide same results. Can anyone help me out to produce same result in php as in python. Thanks.

Turns out that dechex function is not the same as python's hex.
In this case result of hex function was removing dashes from uuid. Solved it with str_replace.

Related

What code it is and how to rewrite in php

i have got this code from one of api provider
Not sure its asp .net or something
Need to convert to php
i tried with some online tools, no luck.
Some One help what code it is and how i can convert to php.
string CrypCode = (DateTime.Now.Year.ToString()+ (Seed + DateTime.Now.DayOfYear.ToString()));
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(CrypCode);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
string KEY = s.ToString();
return KEY;
I remember when i used to work with VB.NET. Hashing is headache. I see you are trying to md5 hash crypcode. In php its simple. Dont know why Microsoft languages long it out. They must have their reasons. Believe it or not in php its one line.
$crypcode = date("Y") + ($seed + date("z"));
$key = md5($crypcode);
return $key;
http://php.net/manual/en/function.md5.php
http://php.net/manual/en/function.date.php
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5cryptoserviceprovider

How does python converts mysql binary(16)

I have two apps one written in php and one in python and both of them use the same mysql database.
For the public id of the entries in some of the tables I use binary(16) fields(I can't change this, it must remain this way).
The question is how does python does the conversion of this binary field?
Let's take one of the entries as an example.
When I get it in php(from the db) the value of the public id is °•WiCÄ‘õ0Iò|–g, the same value is shown in SequelPro. But php myAdmin does a hex function over binary fields and shows 0bb09557691443c491f53049f27c9667. Now I managed in php to convert the binary to the value showed in php myAdmin and it works for all the entries but I've just noticed that python does another conversion. When I get the entry used in this example via python the public id is owwweye1rjnvt3i1d0ib18x3.
What I need to achieve is to convert in php what I get from MySql: °•WiCÄ‘õ0Iò|–g to what python sees: owwweye1rjnvt3i1d0ib18x3. The php app makes calls on the python one(not developed by me) and thus the id needs to be in the same format for a successfull call.
Any suggestions are welcomed. Thanks.
EDIT: If i send °•WiCÄ‘õ0Iò|–g from php to python and print it rigth away I get: °•WiCÄ‘õ0Iò|–g
Finally I've sorted this out.
Seems that python converts to base36 not hex as I've wrongly supposed.
I've tried to simply base_convert 0bb09557691443c491f53049f27c9667 from 16 to 36 but I've got owwweye1rk04k4cskkw4s08s. Not really what I needed but still a great step further as it started to look like owwweye1rjnvt3i1d0ib18x3.
This difference I supposed to appear because of the large values to be converted(loss of precision), so I've further researched and found the bellow function, written by Clifford dot ct at gmail dot com on the php.net website:
<?php
function str_baseconvert($str, $frombase=10, $tobase=36) {
$str = trim($str);
if (intval($frombase) != 10) {
$len = strlen($str);
$q = 0;
for ($i=0; $i<$len; $i++) {
$r = base_convert($str[$i], $frombase, 10);
$q = bcadd(bcmul($q, $frombase), $r);
}
}
else $q = $str;
if (intval($tobase) != 10) {
$s = '';
while (bccomp($q, '0', 0) > 0) {
$r = intval(bcmod($q, $tobase));
$s = base_convert($r, 10, $tobase) . $s;
$q = bcdiv($q, $tobase, 0);
}
}
else $s = $q;
return $s;
}
?>
I don't think others will come across this issue very often, but still if it happens hope they'll find this instead of burning their brains out like I did :))))

Convert FoxPro function to php

I have been asked/told to convert a foxpro function to PHP, however I know nothing about foxpro.
PARAMETERS cCkey
LOCAL cKey
cKey = SUBSTR(SYS(2015),2)+PADL(LTRIM(STR(INT(IIF(INT(RAND()*1000000000) = 851390329,RAND(-1),RAND())*1000000),6)),6,"0")
RETURN cKey
Above is the function they are wanting to use in a system that is being built in php to integrate with the foxpro databases.
Some of the functions are familiar from PHP, but others like the "SYS", and "IIF" are not, and being that I know someone on here will be able to take one look at it, and know exactly what it is doing.
Mind helping me out? Thanks in advance.
Sys(2015) is a handy VFP function which returns a value unique to that session of VFP. You can read it here
Iif is inline if-else-endif statement .. like Excel does
Updated
SYS(2015) in PHP ? I don't know .. but if we talking about random string in PHP, you can use this
function rand_string( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
I got that from this link and got the basic idea from this link
About the other part MAYBE like this :
$randomresult = 0
$srandom = ""
If (INT(RAND()*1000000000) = 851390329)
{
$randomresult = int(rand(-1)) * 1000000
}
else
{
$randomresult = int(rand()) * 1000000
}
$srandom=str_pad(ltrim(strval($randomresult),"0")),6,"0",STR_PAD_LEFT)
So, MAYBE we can make the foxpro code like this in PHP :
$cKey = rand_string(10) . str_pad(ltrim(strval($randomresult),"0")),6,"0",STR_PAD_LEFT)
At least you can the idea .....
SYS(2015) Returns a unique 10-character procedure name that begins with an underscore followed by a combination of letters and numbers.
http://msdn.microsoft.com/en-us/library/684by7c1(v=vs.80).aspx
IIF Returns one of two values depending on the value of a logical expression.
http://msdn.microsoft.com/en-us/library/7ttt15k6(v=vs.80).aspx
With this information I think you can at least take a stab at creating a PHP function and then showing some PHP and asking for help if needed.

Workaround needed, PHP dechex maximum integer [duplicate]

I have some large HEX values that I want to display as regular numbers, I was using hexdec() to convert to float, and I found a function on PHP.net to convert that to decimal, but it seems to hit a ceiling, e.g.:
$h = 'D5CE3E462533364B';
$f = hexdec($h);
echo $f .' = '. Exp_to_dec($f);
Output: 1.5406319846274E+19 = 15406319846274000000
Result from calc.exe = 15406319846273791563
Is there another method to convert large hex values?
As said on the hexdec manual page:
The function can now convert values
that are to big for the platforms
integer type, it will return the value
as float instead in that case.
If you want to get some kind of big integer (not float), you'll need it stored inside a string. This might be possible using BC Math functions.
For instance, if you look in the comments of the hexdec manual page, you'll find this note
If you adapt that function a bit, to avoid a notice, you'll get:
function bchexdec($hex)
{
$dec = 0;
$len = strlen($hex);
for ($i = 1; $i <= $len; $i++) {
$dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
}
return $dec;
}
(This function has been copied from the note I linked to; and only a bit adapted by me)
And using it on your number:
$h = 'D5CE3E462533364B';
$f = bchexdec($h);
var_dump($f);
The output will be:
string '15406319846273791563' (length=20)
So, not the kind of big float you had ; and seems OK with what you are expecting:
Result from calc.exe =
15406319846273791563
Hope this help ;-)
And, yes, user notes on the PHP documentation are sometimes a real gold mine ;-)
hexdec() switches from int to float when the result is too large to be represented as an int. If you want arbitrarily long values, you're probably going to have to roll your own conversion function to change the hex string to a GMP integer.
function gmp_hexdec($n) {
$gmp = gmp_init(0);
$mult = gmp_init(1);
for ($i=strlen($n)-1;$i>=0;$i--,$mult=gmp_mul($mult, 16)) {
$gmp = gmp_add($gmp, gmp_mul($mult, hexdec($n[$i])));
}
return $gmp;
}
print gmp_strval(gmp_hexdec("D5CE3E462533364B"));
Output: 15406319846273791563
$num = gmp_init( '0xD5CE3E462533364B' ); // way to input a number in gmp
echo gmp_strval($num, 10); // display value in decimal
That's the module to use. Convert it to a function and then use on your numbers.
Note: provide these hex numbers as strings so:
$num = "0x348726837469972346"; // set variable
$gmpnum = gmp_init("$num"); // gmp number format
echo gmp_strval($gmpnum, 10); // convert to decimal and print out
1.5406319846274E+19 is a limited representation of you number. You can have a more complete one by using printf()
printf("%u\n", hexdec($h));
...will output "15406319846273792000". PHP uses floats for such big numbers, so you may lose a bit of precision. If you have to work with arbitrary precision numbers, you may try the bcmath extension. By splitting the hex into two 32-bit words (which should be safe on most systems) you should be able to get more precision. For instance:
$f = bcadd(bcmul(hexdec(substr($h, 0, -8)), 0x100000000), hexdec(substr($h, 8)));
...would set $f to 15406319846273791563.
Convert HEX to DEC is easy.. But, reconstruct back hexadecimal number is very hard.
Try to use base_convert ..
$hexadecimal = base_convert(2826896153644826, 10, 16);
// result: a0b0c0d0e0f1a
Run into this issue while storing 64-bit keys in MySQL database. I was able to get a bit perfect conversion to a 64-bit signed integer (PHP limitation) using a few binary operators: (This code is 16x faster than bchexdec function and resulting variables are using half the memory on average).
function x64toSignedInt($k){
$left = hexdec(substr($k,0,8));
$right = hexdec(substr($k,8,8));
return (int) ($left << 32) | $right;
}
MySQL signed BIGINT datatype is a great match for this as an index or storage in general. HEX(column) is a simple way to convert it back to HEX within the SQL query for use elsewhere.
This solution also uses the BC Math Functions. However, an algorithm is used which does without the bcpow function. This function is a bit shorter and faster than the accepted solution, tested on PHP 7.4.
function hexDecBc(string $hex) : string
{
for ($dec = '0', $i = 0; $i < strlen($hex); $i++) {
$dec = bcadd(bcmul($dec,'16'),(string)hexdec($hex[$i]));
}
return $dec;
}
Make sure to enable gmp extension. ext-gmp
$number = gmp_strval(gmp_init('0x03....')); // outputs: 1234324....
Doesn't intval(var, base) take care of it?
From the PHP Manual.

Converting long int to string in PHP

I'm using FMS along with PHP and I need the client's ID in order to disconnect some user at some point. So, I retrieve client's ID from FMS, but FMS sends the ID as a long int, such as 4702111234508538223.
Here's my problem; I need to convert this number to something like oAACAAAA in PHP. Is there any short way or some kind of library exists to doing this? Otherwise I have to convert this AS3 library into PHP.
This function converts something like "4702111234525315439" into something like "oAADAAAA":
function convert_id_to_str($id)
{
if (strspn($id, '0123456789') != strlen($id)) {
return false;
}
$str = '';
if (PHP_INT_SIZE >= 8) {
while ($id) {
$str .= chr($id & 255);
$id >>= 8;
}
} else {
while ($id) {
$str .= chr(bcmod($id, '256'));
$id = bcdiv($id, '256', 0);
}
}
return $str;
}
You could use either BC Math or GMP PHP functionalities to be sure to handle 64-bit number on 32 and 64-bit PHP capable server, and then pack the result in a formatted string, e.g. :
$id = "4702111234508538223";
$hi = bcdiv($id, pow(2, 32));
$lo = bcsub($id, bcmul($hi, pow(2, 32)));
var_dump(pack("LL", $lo, $hi));
Returns string(8) "oAACAAAA".
The code is exploded but could easily be turned to a one-liner or function as well. The use of a big number extension ensure compatibility with 32-bits platforms but if you're sure the platform hosting your PHP interpreter have 64-bit capabilities you could just use
pack("LL", $id, $id / pow(2, 32));

Categories