I have a PHP script that creates a QR code out of a username and timestamp. I need to prove the QR code came from my server so I am encrypting the username and timestamp with a private RSA key. In order to get it into the QR code I am then base64 encoding it.
I am trialling it with Android first. I can get the string out of the QR code but when I base64 decode it in Android, it returns null. After debugging it seems it's because there are two whitespaces in the string. When the decoder comes to check the illegal characters are divisible by 4, it obviously fails. Getting desperate I removed the whitespaces but then it changed the length so the calculations still didn't work out. Can I change the whitespace for a 'safe' character? Or is the particular encode/decode pair not compatible??
PHP code:
$data = base64_encode($username."`".$timestamp);
$fp = fopen("private.pem", "r");
$private_key = fread($fp, 8192);
fclose($fp);
openssl_private_encrypt($data, &$encrypted_data, $private_key);
$encrypted_data_64 = base64_encode($encrypted_data);
// create QR code
Android code:
String s = data.getStringExtra("SCAN_RESULT");
byte[] b = Base64.decode(s.toCharArray());
// b is null at this point
Base64 code that it bugs out on:is
// Check special case
int sLen = str != null ? str.length() : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[str.charAt(i)] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
PHP base64 encode uses the '+' symbol. When this gets put into a QR code, the '+' comes through as space. Replaced ' ' with '+' and it got decoded fine.
Related
I have this PHP code:
$tagId = 1; // the original value of tag
$tagIdAsHex = sprintf("%02X", $tagId); // the tag value in hex format
$tagAsHexBytes = pack('H*', $tagIdAsHex); // the packed hex value of tag packed into string as a conversion
How can I translate that to C++?
byte tagId = 1;
auto hexedTag = IntToHex(tagId); //C++ Builder
??
The PHP code shown is simply converting the integer 1 into a hex-encoded string containing "01", and is then parsing that hex string into a binary string holding a single byte 0x01.
In C, you can use sscanf() in a loop to parse a hex string.
In standard C++, you can use std::hex and std::setw() to parse a hex string from any std::istream, such as std::istringstream, using operator>> in a loop.
In C++Builder specifically, you can use its RTL's HexToBin() function to parse a hex string into a pre-allocated byte array.
I have a slice of php encoded code but I don't know how it encoded i mean by which why they encoded this code when i use unphp.net successfully it decode the code and get the real code
simple of encoded code define("\x53\x54\117\103\113\x5f\103\x48\105\x43\113", false) my question is how i can encode another code to be like this and it by which why is encoded please anyone have a knowledge about tell me or know any tool to suggest
I would need more information for me to be able to discern what obfuscator was actually used to encode this, but for this specific string, it appears to be a mix of hex- and octal- encoded letters
"\x53\x54\117\103\113\x5f\103\x48\105\x43\113"
\xFF - Hex
\000 - Octal
The sequence above is encoded as follows (where x is hex and 8 is octal): xx888x8x8x8
This sequence may be random or intentional. Assuming it's random, the following function may be used to encode any string in like manner using random_int() for selecting encoding method at random.
<?php
function hex_octal_rand_encode($s) {
$result = '';
foreach (str_split($s) as $c) {
$d = ord($c);
// select encoding method at random (0 = hex, 1 = oct)
$result .= (random_int(0, 1) === 0)
? '\\x' . dechex($d)
: '\\' . decoct($d);
}
return $result;
}
// Test
$input = "STOCK_CHECK";
$encoded = hex_octal_rand_encode($input);
echo sprintf("Encoded: %s\n", $encoded);
$cmd = sprintf('return "%s";', $encoded);
echo sprintf("Decoded: %s\n", eval($cmd));
?>
Sample outputs (notice the encoded value changes):
Encoded: \x53\x54\117\103\x4b\137\x43\x48\x45\x43\x4b
Decoded: STOCK_CHECK
Encoded: \x53\124\x4f\x43\113\x5f\x43\110\x45\x43\x4b
Decoded: STOCK_CHECK
Encoded: \123\124\x4f\x43\113\137\x43\x48\105\x43\113
Decoded: STOCK_CHECK
I have the string:
$str = 'ماجد';
This need to be encoded as:
'%E3%C7%CC%CF'
But I cannot figure out how to reach this encoded string. I believe it is Windows-1256. The above encoded string is how it is being encoded by a program I have.
Does anyone know how to reach this string?
If you know you want to use Windows-1256 then all you have to do is to change the encoding of the input string (which is UTF-8) to Windows-1256. Then you apply urlencode() to the returned string and that's all.
There are several ways to change the encoding of a string in PHP. One of them (that I tested and provides the result you expect) is using iconv():
$str = 'ماجد';
$conv = iconv('utf-8', 'windows-1256', $str);
echo(urlencode($conv));
You need to somehow split the string into its hexadecimal representation and then put a % singn in front of the hex number pairs.
<?php
$hexString = bin2hex("ماجد");
for($i = 0; $i < strlen($hexString); $i += 2){
echo "%".substr($hexString, $i, 2);
}
?>
This will do the trick but im sure there is a more elegant way.
I receive data from a PUSH service. This data is compressed with gzcompress(). At the very Beginning of the data, it contains an int which is the length of the data contained. This is done after the gzcompress(); So a sample data would be:
187xœËHÍÉÉ,
Which is produced by
echo '187'.gzcompress('Hello');
Now, I don't know the length of the int, it could be 1 digit it could be 10 digits. I also don't know the first character to find the position of the beginning of a string.
Any ideas on how to retrieve/subtract the int?
$length_value=???
$string_value=???
Assuming that the compressed data would NEVER start with a digit, then a regex would be easiest:
$string = '187xœËHÍÉÉ,';
preg_match('/^(\d+)/', $string, $matches);
$number = $matches[0];
$compressed_data = substr($string, 0, strlen($number));
If the compressed data DOES start with a digit, then you're going to end up with corrupt data - you'll have absolutely no way of differentiating where the 'length' value stops and the compressed data starts, e.g.
$compressed = '123foo';
$length = '6';
$your_string = '6123foo';
Ok - is that a string of length 61, with compressed data 23foo? or 612 + 3foo?
You could use preg_match() to catch the integer at the start of the string.
http://php.net/manual/en/function.preg-match.php
You could do:
$contents = "187xœËHÍÉÉ,";
$length = (int)$contents;
$startingPosition = strlen((string)$length);
$original = gzuncompress(substr($contents, $startingPosition), $length);
But I feel this may fail if the first compressed byte is a number.
I am trying write a PHP function that returns a random string of a given length. I wrote this:
<?
function generate_string($lenght) {
$ret = "";
for ($i = 0; $i < $lenght; $i++) {
$ret .= chr(mt_rand(32,126));
}
return $ret;
}
echo generate_string(150);
?>
The above function generates a random string, but the length of the string is not constant, ie: one time it is 30 characters, the other is 60 (obviously I call it with the same length as input every time). I've searched other examples of random string generators, but they all use a base string to pick letters. I am wondering why this method is not working properly.
Thanks!
Educated guess: you attempt to display your plain text string as HTML. The browser, after being told it's HTML, handles it as such. As soon as a < character is generated, the following characters are rendered as an (unknown) HTML tag and are not displayed as HTML standards mandate.
Fix:
echo htmlspecialchars(generate_string(150));
This is the conclusion i reached after testing it a while : Your functions works correctly. It depends on what you do with the randomly generated string. If you are simply echo-ing it, then it might generate somthing like <ck1ask which will be treated like a tag. Try eliminating certain characters from being concatenated to the string.
This function will work to generate a random string in PHP
function getRandomString($maxlength=12, $isSpecialChar=false)
{
$randomString=null;
//initalise the string include lower case, upper case and numbers
$charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//if required special character to include, please set $isSpecialchar= 1 or true
if ($isSpecialChar) $charSet .= "~##$%^*()_±={}|][";
//loop for get specify length character with random characters
for ($i=0; $i<$maxlength; $i++) $randomString .= $charSet[(mt_rand(0, (strlen($charSet)-1)))];
//return the random string
return $randomString;
}
//call the function set value you required to string length default:12
$random8char=getRandomString(8);
echo $random8char;
Source: Generate random string in php