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
Related
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.
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 :))))
I found this code snippet for PHP and Javascript, but I was wondering if it could be made work in classic asp? Here's a whole article on the topic for reference.
http://24ways.org/2010/calculating-color-contrast/
PHP code
function getContrast50($hexcolor){
return (hexdec($hexcolor) > 0xffffff/2) ? 'black':'white';
}
Well, nothing built into the language. Converting hex to decimal is as easy as CLng("&H" & hexValue) but from quick look in the PHP manual I saw that hexdec() method ignores any invalid characters, while the VBScript CLng() will just crash.
So here is a working function that as far as I can tell doing the same thing:
Function GetContrast50(hexColor)
Const strValidChars = "1234567890abcdef"
Dim maxValue, decValue, sanitizedColor
Dim x, curChar
sanitizedColor = ""
For x=1 To Len(hexColor)
curChar = LCase(Mid(hexColor, x, 1))
If InStr(strValidChars, curChar)>0 Then
sanitizedColor = sanitizedColor & curChar
End If
Next
If Len(sanitizedColor)=0 Then
GetContrast50 = "invalid color string"
Exit Function
End If
maxValue = CLng("&H" & "ffffff")
decValue = CLng("&H" & sanitizedColor)
If decValue > (maxValue / 2) Then
GetContrast50 = "black"
Else
GetContrast50 = "white"
End If
End Function
It's pretty easy to extend the validation to check the given string is in valid range.
So I am working in PHP to convert a Steam Id, which many of you may be familiar with. I have the following steam ID:
STEAM_0:1:1514332
Now, I need to convert this to the 64 bit version, which is also the community ID. After browsing Steams official release on this here: http://developer.valvesoftware.com/wiki/SteamID and after also looking many places online, I have found the following method works for this:
Let X,Y, and Z be defined by the Steam ID: STEAM_X:Y:Z
SteamCommunityID = (Z*2) + 76561197960265728 + Y
So it works! However, where seems to be a mismatch between my ACTUAL community ID, and the one I am generating
Actual: 76561197963294393
PHP generated: 76561197963294000
When reversing the equasion, to get my steam id from the community id, I get: 1514335.5
Here is a simple example of the php in question:
//STEAM_0:1:1514332
$a = (1514332 * 2) + 76561197960265728 + 1;
echo $a; //76561197963294000
Am I doing something wrong?
PHP don't have 64bit int on 32-bit binary. It is using floating point here. see how to have 64 bit integer on PHP?
The question include links to BC Math, which can be used for your problem.
Personally, I use the following code and it works perfectly for splitting the Steam ID and working out the 64-bit community ID:
$split = explode(":", $steamid); // STEAM_?:?:??????? format
$x = substr($split[0], 6, 1);
$y = $split[1];
$z = $split[2];
$w = ($z * 2) + 0x0110000100000000 + $y;
$w will be the correctly formatted ID. I thought this may be helpful since I found this trying to do the same thing :)
I have had the issue. I'm using xampp on windows and its using the 32bit version of php but i just finished making a working script :) it can convert 64bit steamid's to 32bit and back have a mess with it.
<?php
//Starting 64bit steamid
$steamid = "76561198086186258";
echo "Original 64bit steamid: $steamid";
//64bit steamid to 32bit below
$authserver = bcsub($steamid, '76561197960265728') & 1;
$authid = (bcsub($steamid, '76561197960265728')-$authserver)/2;
$steamid = "STEAM_0:$authserver:$authid";
echo "<br/>32bit steamid: $steamid";
//32bit steamid to 64bit below
$id = explode(":", $steamid);
$authserver = $id[1];
$steamid64 = $id[2];
$steamid64 = $steamid64 * 2;
$steamid64 = bcadd($steamid64, 61197960265728);
if ($authserver == 1){$steamid64 = $steamid64 + 1;};
$steamid64 = "765$steamid64";
echo "<br/>new 64bit steamid: $steamid64";
?>
try to add (string) before these calculations
$a = (string) (1514332 * 2) + 76561197960265728 + 1;
and it will work always;
demo
response: 76561197963294393
Using the BCMath extension, you can do the following:
bcadd(bcadd(bcmul('1514332', '2'), '76561197960265728'), 1)
Which is a conversion of the equation above. It returns a string and not an int, thus avoiding the 32bit int problem.
You are not doing anything wrong. The formula is correct (using a calculator I get the 'actual' number).
There must be either a rounding or calculating issue or a simple OS limit for it.
You may use the BC Math PHP extension. Here is a snippet:
//STEAM_0:1:1514332
$a = bcadd(bcadd((1514332 * 2), 76561197960265728), 1);
echo $a; //76561197963294393
Very old topic but just wanted to share how I solved it since I had 32bit PHP and no possibility of using BCMath on my host. (thanks SiPlus for solution)
Here's a snippet:
# Convert Steam ID to Steam64 ID
$idParts = explode(':', $tradeOwnerSteamId32);
$authServer = intval($idParts[1]);
$accountNumber = intval($idParts[2]);
$tradeOwnerSteamId64 = (string) $accountNumber * 2 + $authServer;
//And using it in URL
$depositorInventory = json_decode(file_get_contents("https://steamcommunity.com/profiles/[U:1:$tradeOwnerSteamId64]/inventory/json/730/2"), true);
This is not about security. It is also not to make it hard to break. I'm looking for a simple algorithm to change a string (a url) in a way it does not resemble the original. The encryption will be done with javascript. Then I want to feed the encrypted string to a PHP function to change it back to the original. Both ends could share a secret key, or the conversions could be key-less and rely on just logic.
The ideal solution
will be simple
will use available javascript functions for encryption
will use available php functions for decryption
will produce encrypted string in way not to resemble the plain text at all
will only use lower-case alphabet characters and numbers in the encrypted string
is not a method widely used like Base64-ing as encryption.
Edit: The last requirement was added after shamittomar's answer.
You can use bitwise XOR in javascript to encode the string and again in PHP to decode it again. I wrote a little Javascript example for you. It works the same in PHP. If you call enc() a second time with the already encoded string, you'll get the original string again.
<html>
<head><title></title></head>
<body>
<script type="text/javascript">
function enc(str) {
var encoded = "";
for (i=0; i<str.length;i++) {
var a = str.charCodeAt(i);
var b = a ^ 123; // bitwise XOR with any number, e.g. 123
encoded = encoded+String.fromCharCode(b);
}
return encoded;
}
var str = "hello world";
var encoded = enc(str);
alert(encoded); // shows encoded string
alert(enc(encoded)); // shows the original string again
</script>
</body>
</html>
In PHP do something like this (caution, this is not tested and it's been a long while since I did PHP):
$encoded = "..."; // <-- encoded string from the request
$decoded = "";
for( $i = 0; $i < strlen($encoded); $i++ ) {
$b = ord($encoded[$i]);
$a = $b ^ 123; // <-- must be same number used to encode the character
$decoded .= chr($a)
}
echo $decoded;
If that's what you want, you can Base64 encode and decode that.
[EDIT]: After OP clarification:
As you do not want widely used methods, here is one rarely used method and that can do it for you by giving output only in LOWERCASE letters and NUMBERS. It is Base32 Encode/Decode. Use the following libraries:
Javascript Base32 Encoder: http://www.tumuski.com/2010/04/nibbler/
PHP Base32 Decoder: https://www.phpclasses.org/package/3484-PHP-Encode-and-decode-data-with-MIME-base-32-encoding.html
If it's not about security, and not about making it hard to break, then how about ROT-13?
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/string/rot13 [rev. #1]
String.prototype.rot13 = function(){
return this.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
};
...
var s = "My String";
var enc = s.rot13(); // encrypted value in enc
PHP has a native function, str_rot13: http://php.net/manual/en/function.str-rot13.php
$decrypted = str_rot13($_GET['whatever']);
Well I found this page and found Redcully's program not work for me so I thought It happens with all others. finally I got reason and fixed it. Here new code is...
Thanks to Redcully :)
JS function:
function encode(str) {
var encoded = "";
for (i=0; i<str.length;i++) {
var a = str.charCodeAt(i);
var b = a ^ 51; // bitwise XOR with any number, e.g. 123
encoded = encoded+String.fromCharCode(b);
}
return encoded;
}
PHP function:
function decode($encoded) {
$decoded = "";
for( $i = 0; $i < strlen($encoded); $i++ ) {
$b = ord($encoded[$i]);
$a = $b ^ 51; // <-- must be same number used to encode the character
$decoded .= chr($a);
}
return $decoded;
}
How are you planning to implement (hide) the secret in Javascript? IMHO it's not possible.
Edit: OK - not about security.. then just use any baseXX or rot encoding mechanism. But you can't really say one of these algorythms would not be well known...