PHP Encryption, encrypts with empty line in mind - php

I'm working with some encryption in PHP that's being accessed by some c# code,
When I sha1 Encrypt the following: test1:test1:apple,
every online generator will return: 8ee27a0e9368d2835b3fdeb4b50caf1d8f790314
However, when I run my PHP script it returns 296b39344a6eb9d88c3bb1122f5941f0bcf3b0c2 instead. Because essentially it's adding an empty line along with the string (test1:test1:apple) that I'm encrypting.
Does anyone have any idea how to fix this? It's not neccesarily the worst thing in the world, it's just extremely annoying.
The code I'm using is pretty simple:
function GetRandomWord()
{
$file = "../Core/nouns0.txt";
$file_arr = file($file);
$num_lines = count($file_arr);
$last_index = $num_lines -1;
$rand_index = rand(0, $last_index);
$rand_text = $file_arr[$rand_index];
return $rand_text;
}
$enc = GetRandomWord();
$encrypted = sha1("$username:$password:$enc");
echo $encrypted;
which gets caught in c# by a script.
Thanks in advance!

#IƂyaBursov their answer helped! I changed the GetRandomWord() function's return statement to
return trim($rand_text);
Thanks!

file() will read each line of a file into an array. It reads the entire line, including the linefeed at the end. If you don't want this behaviour, use the second argument to say so:
$file_arr = file($file, FILE_IGNORE_NEW_LINES);

Related

PHP Script - Comment/Uncomment line

Could anyone give me some ideas or solution for toggling comments in file?
To read value and toggle comment/uncomment in that line where value resides.
For example, I would like to include class Model and initialize it.
In some file there are prepared includes and initializations:
//include('foo/Model.php');
//$model = new Model();
Function is needed, for those who can not understand what the question is.
How to uncomment?
Thanks for adding more insights to your question! Actually it's a pretty interesting one.
As far as I understand you're looking for a dynamic way to comment/uncomment lines inside a file.
So let's define our parameters first:
We want to manipulate a specific file (we need the filename)
We want to toggle specific line numbers inside this file (list of line numbers)
function file_toggler(string $file, array $lineNumbers)
With this in mind I we need to read a file and split their lines into line numbers. PHP provides a handy function for this called file().
file(): Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.
With this in mind we have everything what we need to write a function:
<?php
function file_toggler(string $file, array $lineNumbers)
{
// normalize because file() starts with 0 and
// a regular user would use (1) as the first number
$lineNumbers = array_map(function ($number) {
return $number - 1;
}, $lineNumbers);
// get all lines and trim them because
// file() keeps newlines inside each line
$lines = array_map('trim', file($file));
// now we can take the line numbers and
// check if it starts with a comment.
foreach ($lineNumbers as $lineNumber) {
$line = trim($lines[$lineNumber]);
if (substr($line, 0, 2) == '//') {
$line = substr($line, 2);
} else {
$line = '//' . $line;
}
// replace the lines with the toggled value
$lines[$lineNumber] = $line;
}
// finally we write the lines to the file
// I'm using implode() which will append a "\n" to every
// entry inside the array and return it as a string.
file_put_contents($file, implode(PHP_EOL, $lines));
}
toggleFileComments(__DIR__ . '/file1.php', [3, 4]);
Hope it helps :-)

Create n-level multidimensional array in PHP from String

To get the right position I have to access in a tree array I'm working on a solution to bring an exploded string (with numeric keys, separated by "." (dot) - like in an register) to an array ...
$string = '1.3.2.5';
so the returning value should be an array with
$array[1][3][2][5] = 'x';
where x can hold any data or be empty
Here's a quick and dirty solution using eval(). I need to quote Rasmus Lerdorf here:
If eval() is the answer, you're almost certainly asking the wrong
question.
So, no, I am not happy with this answer, but it does work. Keep in mind that if the input comes from the users you might give them unwanted control over your server. It is very easy to do:
$test = 'x; rmdir($_SERVER["HOME"]);';. Do not use this on your server!
So be careful with this.
<?php
$string = '1.3.2.5';
$test = 'x';
$array = [];
function setArray($address,$value)
{
global $array;
eval('$array['.str_replace('.','][',$address).'] = $value;');
}
function getArray($address)
{
global $array;
eval('$value = $array['.str_replace('.','][',$address).'];');
return $value;
}
setArray($string,$test);
echo getArray($string);
echo '<pre>';
var_dump($array);
echo '</pre>';
Note that this will work with any address length > 1. Also note that you can overwrite a complete tree, accidentally, if you use a short address.
Who can find a good solution without eval()?

Is there any manual method other than "str_repeat" to repeat the string?

I mean if we give 3, b as parameters passed into function, it should return "bbb" by using loops.
I've tried some code, but I do not want to post it because it might look crazy for a well-versed developer. I can provide you links, this question has been asked in an interview, mainly they want it to be computed in C or C++. Since I am a PHP practitioner, I am curious to know it is possible in PHP. Below is the link (ROUND 2: SIMPLE CODING(3 hours))
https://www.geeksforgeeks.org/zoho-interview-set-3-campus/
A PHP function to do that would probably look like this:
function string_repeat($num, $string)
{
$result = "";
for ($x = 0; $x < $num; $x++) {
$result .= $string;
}
return $result;
}
So calling echo string_repeat(3, 'b'); would output:
bbb
One way would be to keep around a "dummy" string, of sufficient length to be longer than any string you want to generate. Then, we can use preg_replace to replace each character with whatever the input is. Finally, we can substring that replace string to the desired length.
$dummy = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$length = 3;
$dummy = preg_replace('/./', 'b', $dummy);
$output = substr($dummy, 0, $length);
echo $output;
This prints:
bbb
You could wrap this into a helper function, if you really wanted to do that. Note that internally the regex engine is most likely doing some looping of its own, so we are not really freeing ourselves from looping, just hiding it from the current context.

PHP check if contents are available

I am using random.org in my php script to generate random numbers like that:
function getToken($length){
$r = explode('
',file_get_contents('http://www.random.org/integers/?num='.$length.'&min=0&max=9&col=1&base=10&format=plain'));
$string = '';
foreach ( $r as $char ) $string.=$char;
return $string;
}
but my university net denies such queries, so whenewer i test my project using university wifi, i dont get random numbers to be generated, and that means trouble.
So, i before using this function, it needs to be chect if i can query random.org or not like that:
if( site is accessible ) return getToken();
else return false;
what would be the best way to check accesability?
Myself i tried:
file_get_contents();
but it sends warnings,whenewer it fails,
dns_get_record();
but i dont know if i can trust that, if it checks only dns name.
Please help!
P.S. a pinging technique might proove usefull...
You could just run file_get_contents with # to supress errors and simply return when it doesn't give you a random number, resulting in something like:
function getToken($length){
$number = #file_get_contents('http://www.random.org/integers/?num='.$length.'&min=0&max=9&col=1&base=10&format=plain');
if($number === false) return null;
$r = explode('',$number);
$string = '';
foreach ( $r as $char ) $string.=$char;
return $string;
}
That being said, I seriously doubt if you really need to use random.org to generate random numbers. PHP's own pseudo-random generator functions include openssl_random_pseudo_bytes that is said to generate "cryptographically strong" pseudorandom numbers:
http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php

How to change php 5.2 mhash codes to php5.3 hash

Friends my php 5.2 codes am keeping my password like this
echo '<br>'.base64_encode(mhash(MHASH_MD5,'test'));
result CY9rzUYh03PK3k6DJie09g==
In php 5.3 mhash extension is obsoleted by Hash like I saw in there documentation. So I tried like this. But its giving wrong result.
echo '<br>'.base64_encode(hash(MD5,'test'));
result MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=
Please help me to convert my 5.2 mhash codes to 5.3.
Thanks
Actually, they are the same, only in a different format.
The first one is binary data, while the second one is hexadecimal.
You can convert the first one to the second using this function:
$second_hash = bin2hex ($first_hash);
Or the other way around:
$first_hash = hex2bin ($second_hash);
Update
Add this function:
define('HEX2BIN_WS', " \t\n\r");
function hex2bin($hex_string) {
$pos = 0;
$result = '';
while ($pos < strlen($hex_string)) {
if (strpos(HEX2BIN_WS, $hex_string{$pos}) !== FALSE) {
$pos++;
} else {
$code = hexdec(substr($hex_string, $pos, 2));
$pos = $pos + 2;
$result .= chr($code);
}
}
return $result;
}
If you want to update obsolete mhash() method to hash_hmac() method using sha1, simply replace :
mhash(MHASH_SHA1, $data, $key)
into
hash_hmac('sha1', $data,$key,true)
In my context i was faced to old piece of code
base64_encode(mhash(MHASH_SHA1, $data, $key));
which i replaced by
base64_encode(hash_hmac('sha1', $data,$key,true));
I hope it could help.
mhash(MHASH_MD5, 'FOOBAR'); // what you have
pack('H*', hash(MD5, 'FOOBAR')) // what you accepted
pack('H*', md5('FOOBAR')); // ...
md5('FOOBAR', true); // what you could/should have used
I know this question is rather old but today I had the same problem. Based on this post I was able to find a shorter and I guess more performant way which is worth sharing in my opinion.

Categories