Following are some individual JavaScript statements from a block of java-script code. I want to convert this JavaScript code in PHP so that I can execute it server-side. In the following snippet, there are some operators used, such as >>, >>>, ~, ^, <<, <<<, etc.
How can I translate these JavaScript functions to PHP?
function core_enc(K, F) {
K[F >> 5] |= 128 << ((F) %32);
K[(((F + 64) >>> 9) << 4) + 14] = F;
}
function enc_ff(C, B, G, F, A, E, D) {
return enc_cmn((B & G) | ((~B) & F), C, B, A, E, D);
}
function enc_hh(C, B, G, F, A, E, D) {
return enc_cmn(B ^ G ^ F, C, B, A, E, D);
}
function safe_add(A, D) {
var C = (A & 65535) + (D & 65535);
var B = (A >> 16) + (D >> 16) + (C >> 16);
return (B << 16) | (C & 65535);
}
function bit_rol(A, B) {
return (A << B) | (A >>> (32 - B));
}
That would be the exact same operators. See http://codepad.org/b5uZPCu4 for a demo.
The shift operators >> and << can be directly translated, as well as other basic bitwise operations such as | (or), & (and), ^ (xor), ~ (not), etcetera. PHP arrays also work in the same fashion, and the functions have about the same syntax. Your JavaScript code should work perfectly in PHP with minimal changes (e.g. variableName becomes $variableName, you remove var, and >>> doesn't work in PHP.)
Edit: If this is actually code for MD5 or something, PHP provides the convenient function md5 to do that for you.
Related
Good day,
Trust all is well.
I want to duplicate the Move function from Pascal to PHP.
Here is what I have In Pascal:
function Encode(const S: AnsiString): AnsiString;
const
Map: array [0 .. 63] of Char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz0123456789+/';
var
i: LongInt;
begin
i := 0; ;
Move(S[1], i, Length(S));
Result := Map[i mod 64] + Map[(i shr 6) mod 64];
end;
Here is what I have in PHP:
private function Encode($pass)
{
$map = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/');
$i = 0;
$this->MoveFunction($pass[0], $i, mb_strlen($pass));
$result = $map[$i % 63] . $map[($i >> 6) % 64];
return $result;
}
Now I now know that the Move function is used to copy a section of memory from one place to another, just not sure where to begin and how it would be done. I could not replicate the results from Pascal in PHP. I have tried sub strings ens. to no avail.
The "$this->MoveFunction" is the function that I will need to write in order to duplicate the functionality of the Move function from pascal. I need to use the same outcome of the Move from pascal in order to use the same encryption field from a similar DB.
I think this is an easy way to test in Pascal:
var
A: array[1..4] of Char;
B: Integer;
begin
A[1] := 'W';
A[2] := 'H';
A[3] := 'A';
A[4] := 'T';
B := 5;
Move(A, B, SizeOf(B));
showmessage(B.ToString()); // 4718679
Any help would be greatly appreciated.
Thank you in advance.
Pascal code moves some AnsiChars into 32-bit Int variable. Note that the first char becomes the least significant byte of integer (due to byte order), and result is just equal to
Result := Map[Byte(S[1]) mod 64];
so Move is not needed at all, all other symbols of string aren't involved in work.
If you can cast the first symbol of $pass as byte/int variable in PHP - work is done.
P.S. I see ord() function, so code might look like this:
(I also changed % to bitwise &)
private function Encode($pass)
{
$map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$i = ord($pass[0]);
$result = $map[$i & 63];
return $result;
}
For shr:
Result := Map[i mod 64] + Map[(i shr 6) mod 64]; =>
$a = ord($pass[0]) & 63;
$b = ord($pass[0]) >> 6; //two ms bits
$b = $b & 3; //to clear ms bits
$c = ord($pass[1]) & 15; //four ls bits
$d = $b | ($c << 2); //combine them
$result = $map[$a].$map[$d];
I am trying to implement a python encription code based on gzip and crypto library but i dont know the equivalent modules or functions in either php or node js
from Crypto.Cipher import DES, AES
def enclen(p):
return ((16 - p % 16) & 0xF) + p + 4
def rsb(a, b):
return (0 - a + b) & 0xffffffff
def ands(a, b):
return (a & b) & 0xffffffff
def _ror(val, bits, bit_size):
return ((val & (2 ** bit_size - 1)) >> bits % bit_size) | \
(val << (bit_size - (bits % bit_size)) & (2 ** bit_size - 1))
def __ROR4__(a, b):
return _ror(a, b, 32)
def eor(a, b):
return (a ^ b) & 0xffffffff
class Crypto(object):
def __init__(self):
self.key = b'!*ss!_defaul%t54'
self.kl = 0x10
self.sbox0 = bytes.fromhex(
'637C777BF26B6FC53001672BFED7AB76CA82C97DFA5947F0ADD4A2AF9CA472'
'C0B7FD9326363FF7CC34A5E5F171D8311504C723C31896059A071280E2EB27'
'B27509832C1A1B6E5AA0523BD6B329E32F8453D100ED20FCB15B6ACBBE394A'
'4C58CFD0EFAAFB434D338545F9027F503C9FA851A3408F929D38F5BCB6DA21'
'10FFF3D2CD0C13EC5F974417C4A77E3D645D197360814FDC222A908846EEB8'
'14DE5E0BDBE0323A0A4906245CC2D3AC629195E479E7C8376D8DD54EA96C56'
'F4EA657AAE08BA78252E1CA6B4C6E8DD741F4BBD8B8A703EB5664803F60E61'
'3557B986C11D9EE1F8981169D98E949B1E87E9CE5528DF8CA1890DBFE64268'
'41992D0FB054BB16')
self.plen = 0
def crypt(self, payload):
if not isinstance(payload, bytes):
payload = payload.encode('utf8')
self.plen = len(payload)
i = 0
r = [00] * 16
while i < self.kl:
a = self.key[i]
r[i] = self.sbox0[a]
i += 1
t = int.from_bytes(r[:4], 'big')
r[:4] = int.to_bytes(t, 4, 'little')
t = int.from_bytes(r[4:8], 'big')
r[4:8] = int.to_bytes(t, 4, 'little')
t = int.from_bytes(r[8:12], 'big')
r[8:12] = int.to_bytes(t, 4, 'little')
t = int.from_bytes(r[12:16], 'big')
r[12:16] = int.to_bytes(t, 4, 'little')
b = rsb(self.plen, 0)
b = ands(b, 0xf)
c = b + self.plen + 4
result = [00] * enclen(self.plen)
result[0] = 0x74
result[1] = 0x63
result[2] = 0x02
result[3] = b
result[4:len(payload) + 4] = payload
i = 4
while i != c:
a = result[i]
result[i] = self.sbox0[a]
i += 1
a = c - 4
b = 0
a = a >> 4
d = 4
while b < a:
c = int.from_bytes(result[d:d + 4], 'big')
e = int.from_bytes(r[:4], 'little')
c ^= e
result[d:d + 4] = int.to_bytes(c, 4, 'big')
c = int.from_bytes(result[d + 4:d + 8], 'big')
e = int.from_bytes(r[4:8], 'little')
c = eor(e, __ROR4__(c, 24))
result[d + 4:d + 8] = int.to_bytes(c, 4, 'big')
c = int.from_bytes(result[d + 8:d + 12], 'big')
e = int.from_bytes(r[8:12], 'little')
c = eor(e, __ROR4__(c, 16))
result[d + 8:d + 12] = int.to_bytes(c, 4, 'big')
c = int.from_bytes(result[d + 12:d + 16], 'big')
e = int.from_bytes(r[12:16], 'little')
c = eor(e, __ROR4__(c, 8))
result[d + 12:d + 16] = int.to_bytes(c, 4, 'big')
b += 1
d += 0x10
return bytes(result)
I dont have much idea what really goes behind this code some byte size operations but i dont know what exactly happens
Either nodejs or php equivalent of this code or any idea to how to implement it in those lang or if those languages are supported this kind of operations I dont know
Node.js has really good modules that can handle compression and encryption.
Crypto for cryptography related operations. It supports many algorithms to encrypt/hash stuff
Zlib for compression. Supports algorithms like gzip, deflate, zip, etc...
The docs also include examples on how to use these modules, so make sure to check them
I have a python script and a PHP script what I need is execute the python script through PHP and should get the return value of python code back to PHP.Here is my codes
<?php
$result1= passthru("python E:\naive-bayes-classifier-master\naiveBayesClassifier\return.py");
echo "return value is: $result1" . "\n";
?>
I execute this through another php script using a submit button
and here is the python code
def add(a, b):
# print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
#print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
#print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
# print "DIVIDING %d / %d" % (a, b)
return a / b
if __name__ == '__main__':
divide(10,2)
the result I am getting is
return value is:
there no any value.Please help.Thank you in advance. :)
Finally I found the answer for this problem.In python code I only return the value.But It should be printed too.So here is the modified python code.Hope this will be useful to all of you.
def add(a, b):
# print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
#print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
#print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
# print "DIVIDING %d / %d" % (a, b)
return a / b
if __name__ == '__main__':
ret= divide(10,2)
print("ret:",ret)
I'm searching for an algorithm to solve differences of the type ab-cd, where a, b, c, and d are integers at the edge of the type capacity, i.e. ab overflows or loses digits depending on the actual representation on the machine. I cannot use arbitrary precision math; one of the platforms will be a SQL database.
I consider something like decomposing the product into (a'+a'')b-(c'+c'')d and then somehow iterate the way down. But probably there is a much more efficient method or at least a clever idea how to do the decomposition. Unfortunately in most cases a,b; c,d; a,c; b,d are coprime, so reduction at least is not simple.
Any ideas?
WARNING
This method is only partially functional. There are cases that it can't solve.
Taken from your text:
I'm searching for an algorithm to solve differences of the type ab-cd,
where a, b, c, and d are integers at the edge of the type capacity,
As I understand you want to calculate (a * b) - (c * d) avoiding a numeric overflow. And you want to solve this with an algorithm.
The first thing we need to recognize is that the result of (a * b) - (c * d) may not fit in the data type. I'll not try to solve those cases.
So, I'll search for different ways to calculate "ab-cd". What I've found is this:
(a * b) - (c * d) = ((a - c) * b) - (c * (d - b))
You can re-order the variables to get different products and therfore increasing the chance of finding a case that will allow you to calculate the operation without the dreaded numeric overflow:
((a - d) * b) - (d * (c - b))
((b - c) * a) - (c * (d - a))
((a - c) * b) - (c * (d - b))
((b - d) * c) - (b * (c - a))
((a - d) * c) - (a * (c - b))
((b - c) * d) - (b * (d - a))
((a - c) * d) - (a * (d - b))
Also notice that this are still differences of products, meaning that you can apply them recursively until you find one that works. For example:
Starting with:
(a * b) - (c * d)
=>
Using the transformation:
((a - d) * b) - (d * (c - b))
=>
By substitution:
(e * b) - (d * f)
=>
Rinse an repeat:
((e - f) * b) - (f * (d - b))
Of course we need to make sure we aren't going to run into a numeric overflow by doing this. Thankfully it is also possible to test if a particular product will cause a numeric overflow (without actually doing the product) with the following approach:
var max = MaxValue;
var min = MinValue;
if (a == 0 || b == 0)
{
return false;
}
else
{
var lim = a < 0 != b < 0 ? min : max;
if ((a < 0 == b < 0) == a < 0)
{
return lim / a > b;
}
else
{
return lim / a < b;
}
}
Also, it is also possible to test if a particular difference will cause a numeric overflow (without actually doing the difference) with the following approach:
var max = MaxValue;
var min = MinValue;
if (a < 0 == b < 0)
{
return true;
}
else
{
if (a < 0)
{
if (b > 0)
{
return min + b < a;
}
else
{
return min - b < a;
}
}
else
{
if (b > 0)
{
return max - b > a;
}
else
{
return max + b > a;
}
}
}
With that it is possible to pick an expression from the eight above that will allow you to calculate without the numeric overflow.
But... Sometimes none of those works. And it seems to be that there are cases where not even their combinations works (ie. rinse and repeat dosn't work)*. Maybe there are other identities that can complete the picture.
*: I did try using some heuristic to explore the combinations and also did try random exploration, there is the risk that I didn't pick good heuristics and I didn't have "luck" with the random. That's why I can't tell for sure.
I want to think that I've done some progress... But with respect to the original problem I've ultimately failed. May be I'll get back to this problem when I have more time... or may be I'll just play video games.
The standard way I know of to address this type of issues is to do what humans do with numbers beyond one digit, which is the limit of our natural counting with fingers. We carry numbers forward.
For example, let's say the limit of numbers in your numeric calculator is 256 (2^8). To get the difference of (243*244)-(242*245), we would need to decompose the numbers into
Label | Part 1 (shifted 2 right) | Part 2 (remainder)
a 2 43
b 2 44
c 2 42
d 2 45
You'd need an array to store the individual digits of the result, or a string. I think an array is faster, but a string more convenient and visible (for debugging).
(a*b)-(c*d)
=> a1*b1 shift4 + a1*b2 shift2 + a2*b1 shift2 + a2*b2
- c1*d1 shift4 + c1*d2 shift2 + c2*d1 shift2 + c2*d2
=> 987654321 (right-aligned string positioning)
+ 4xxxx
+ 88xx
+ 86xx
+ 1892
- 4xxxx
- 90xx
- 84xx
- 1890
==========
2
A naive implementation would work through each step independently, pushing each digit into place and carrying it forward where necessary. There are probably tomes of literature about optimizing these algorithms, such as breaking this into array slots of 2 digits each (since your register of number-limit 256 can handle the addition of 2 2-digit numbers easily).
If your products are near the limits of Int32 you can use Int64.
You can use BC Math Functions to work with large number which on both 32 bit & 64 bit systems
Example Of Large Numbers
$a = "4543534543543534543543543543545";
$b = "9354354546546756765756765767676";
$c = "5654656565656556565654656565656";
$d = "4556565656546546546546546356435" ;
var_dump(calculate($a, $b, $c, $d));
Output
string '257010385579862137851193415136408786476450997824338960635377204776397393100227657735978132009487561885957134796870587800' (length=120)
Function Used
function calculate($a, $b, $c, $d)
{
return bcmul(bcmul(bcmul(bcsub($a, $c),bcsub($a, $d)),bcsub($b, $c)),bcsub($b, $d));
}
After playing a little bit more I found a simpler algorithm following my original idea. It may be somewhat slower than the combined multiplication because it requires real multiplication and division instead of only shifts and addition, but I didn't benchmark it so far concerning the performance in an abstract language.
The idea is the following rewrite ab-cd = (a'+q*d)b-cd = a'b-(c-qb)d = a'b-c'd
The algorithm seems to convert the fastest if you order ab-cd as a>b and c>d, i.e. reduce the biggest numbers and maximize q.
q=(int)floor((a>c)? a/d : c/b);
a -= q*d;
c -= q*b;
Now reorder and start again. You can finish as soon as all numbers are small enough for safe multiplication, any number becomes smaller than 2 or even negative, or you find the same value for any of the numbers on both sides.
http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(v) - 1) * CHAR_BIT; // count
This is the same problem in Python: Python equivalent of C code from Bit Twiddling Hacks?
I need to use this code in PHP, independently from integer size (the above code works up to 128-bit integers, which will do fine for me). Here's what I tried:
function countSetBits($int) {
$mask = (1 << PHP_INT_SIZE*8) - 1;
$int = $int - (($int >> 1) & (int) $mask/3);
$int = ($int & ((int) $mask/15)*3) + (($int >> 2) & ((int) $mask/15)*3);
$int = ($int + ($int >> 4)) & ((int) $mask/255)*15;
return ($mask & $int * ((int) $mask/255)) >> ((int) PHP_INT_SIZE - 1) * 8;
}
The reason this doesn't work (on a 64-bit machine with 64-bit PHP - Debian Squeeze) is that PHP doesn't seem to support 64-bit unsigned integers (how to have 64 bit integer on PHP?). I'm afraid I will have to use an arbitrary-precision math library. Or is there another way?
For now, this is what I used:
function countSetBits($int) {
return substr_count(base_convert($int, 10, 2), '1');
}
Try to use the following in your php script before 64-bit operations:
ini_set('precision', 20);