I have an array of hex code in this format
FF8FFE00+++++
The above example is just one string, with + representing the rest of the over 60k long hex code (no use in hogging your broswer). The format looks exactly like that. So let's say
$a = 'FFD8FF++++ string';
echo base64_encode($a);
When printing the above, it takes the hex code as a string and generates the base64 out of the string instead of the hexdec
Looked all over, but it just seems that there are either conversions that make the hex code get hex encoded as well.
In NPP+ i converted a the string to ASCII then encoded in base64 and the result was the expected one (base64 that i can use for an image).
Any idea how I can tell php that the string is actually hex node, not a string?
With hex2bin you can transform a string containing hexadecimals into binary data (stored as a string in PHP). After that encode the binary string to base64 format.
$hex = 'FFD8FF'; // and much more hex values as string as in your example
$bin = hex2bin($hex); // convert the hex values to binary data stored as a PHP string
$b64 = base64_encode($bin); // this contains the base64 representation of the binary data
string(4) "/9j/"
Related
I'm trying to implement the Google Safebrowsing update API v4 in PHP.
But I can't figure how to correctly decode the rawHashes.
(The rawHashes are 4-bytes-truncated sha256 hashes and then concatenated).
I am trying the native base64_decode of PHP but I can't fully decode the string, and I don't know what the next step is.
According to the API documentation here's how the rawhashes are encoded :
string (bytes format)
The hashes, in binary format, concatenated into one long string. Hashes are sorted in lexicographic order. For JSON API users, hashes are base64-encoded.
A base64-encoded string.
I an very simply decoding the string like so:
$decoded = base64_decode($rawHashes);
The base64 encoded string look like this:
"AAAIYAAAC90AABOxAAAjDgAALZIAAEbKAABIHwAA..."
And the base64 decoded string look like this:
b"\x00\x00\x08`\x00\x00\vÝ\x00\x00\x13±\x00\x00#\x0E\x00\x00-’\x00\x00FÊ\x00\x00H\x1F\x00\x00^\x06\x00\x00bF\x00\x00h²"
As you can see something is not right and I must have missed a step but I can't figure which one.
As Mjh said in the discussion nothing is wrong about base64_decode and nothing else is needed.
Nothing's wrong. You just aren't reading carefully. Here, read what it says: The hashes, in binary format. It says binary format. After decoding, you got binary representation of the data. Using bin2hex should return a human-readable hash. $hash = bin2hex(base64_decode($your_encoded_hash)); - Mjh
The decoded string was looking weird as it is binary data (Raw SHA256 hash) although it is totally correct. To get the hashes in a more convenient encoding it's possible to convert the binary represented data to hex represented data with the php function bin2hex
$hash = bin2hex(base64_decode($your_encoded_hash));
From what I know of base64_decode, it just works. Something must be wrong in your $rawHashes string. If you have line breaks in your string, you need to get rid of them by replacing them with an empty string. The hash that base64_decode needs should be one long line of base64 encoded string. It is not uncommon to receive a hash that is broken into multiple lines.
Try this ...
$decoded = base64_decode(str_replace(PHP_EOL, "", $rawHashes));
I want to encode my urls in base64 and decode it in my functions and no body can decode it how can i do this.
<?php
$somestring = 'here is my some string';
$url = 'http://google.com/'.$somestring;
base64_encode($url);
?>
Base64 is not meant for encrypting sensible data. It's merely a means of representing data in another way. What it does, it takes binary data and converts it to ASCII, so that binary data can be represented with ASCII characters.
If you want to encrypt strings like your URLs, you have to choose an encryption algorithm like Blowfish, which is available in the PHP bcrypt extension.
The php manual says that hex2bin() returns a string with a binary representation.
I have this code:
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
The output is:
string 'example hex data' (length=16)
Pardon me if I'm wrong but I believe that the output isn't a binary string??
Did the manual made an error, or am I missing something?
-------------edit------------
Is 'example hex data' a binary representation of data?
hex2bin turns hexadecimal numbers into raw bytes. These raw bytes output to the screen will be interpreted by your browser and/or CLI, which will turn it into text. bin2hex does not return a string like "01001000101" if that's what you expected; that'd be an ASCII representation of a binary string, not a binary string. See for example this if that's what you want: How to see binary representation of variable
From php manual:
"This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function."
"Decodes a hexadecimally encoded (binary) string" and "Returns the binary representation of the given data"
(machine code ie. what's written to disk or processed by the computer hardware)
To answer your question:
Yes 'example hex data' is a (decoded) binary representation of (the given text) data.
The hex (encoded) representation of the same data is 6578616d706c65206865782064617461.
To display the binary (base 2) equivalent of the above hex (base 16) number, you'd base_convert() it (to get a string of 0s & 1s; the ASCII codes/representation)
The confusion seems to arise between the results of hex2bin and base_convert().
As an example:
Some data on disk can be displayed (on console) as 'A' bin2hex
would return this (encoded) as '41' (hex representation).
base_convert() would return this (same) data as '01000001'
hex2bin would then decode this '41' to the machine (ASCII)
code equivalent 'A' (the binary representation, which may be written to disk as binary data)
I have data stored in an SQLite database as BINARY(16), the value of which is determined by PHP's hex2bin function on a 32-character hexadecimal string.
As an example, the string 434e405b823445c09cb6c359fb1b7918 returns CN#[4EÀ¶ÃYûy.
The data stored in this database needs to be manipulated by JavaScript, and to do so I've used the following function (adapted from Andris's answer here):
// Convert hexadecimal to binary string
String.prototype.hex2bin = function ()
{
// Define the variables
var i = 0, l = this.length - 1, bytes = []
// Iterate over the nibbles and convert to binary string
for (i; i < l; i += 2)
{
bytes.push(parseInt(this.substr(i, 2), 16))
}
// Return the binary string
return String.fromCharCode.apply(String, bytes)
}
This works as expected, returning CN#[4EÀ¶ÃYûy from 434e405b823445c09cb6c359fb1b7918.
The problem I have, however, is that when dealing directly with the data returned by PHP's hex2bin function I am given the string CN#[�4E����Y�y rather than CN#[4EÀ¶ÃYûy. This is making it impossible for me to work between the two (for context, JavaScript is being used to power an offline iPad app that works with data retrieved from a PHP web app) as I need to be able to use JavaScript to generate a 32-character hexadecimal string, convert it to a binary string, and have it work with PHP's hex2bin function (and SQLite's HEX function).
This issue, I believe, is that JavaScript uses UTF-16 whereas the binary string is stored as utf8_unicode_ci. My initial thought, then, was that I need to convert the string to UTF-8. Using a Google search led me to here and searching StackOverflow led me to bobince's answer here, both of which recommend using unescape(encodeURIComponent(str)). However, this does return what I need (CN#[�4E����Y�y):
// CN#[Â4EöÃYûy
unescape(encodeURIComponent('434e405b823445c09cb6c359fb1b7918'.hex2bin()))
My question, then, is:
How can I use JavaScript to convert a hexadecimal string into a UTF-8 binary string?
Given a hex-encoded UTF-8 string, `hex',
hex.replace(/../g, '%$&')
will produce a URI-encoded UTF-8 string.
decodeURIComponent converts URI-encoded UTF-8 sequences into JavaScript UTF-16 encoded strings, so
decodeURIComponent(hex.replace(/../g, '%$&'))
should decode a properly hex-encoded UTF-8 string.
You can see that it works by applying it to the example from the hex2bin documentation.
alert(decodeURIComponent('6578616d706c65206865782064617461'.replace(/../g, '%$&')));
// alerts "example hex data"
The string you gave is not UTF-8 encoded though. Specifically,
434e405b823445c09cb6c359fb1b7918
^
82 must follow a byte with at least the first two bits set, and 5b is not such a byte.
RFC 2279 explains:
The table below summarizes the format of these different octet types.
The letter x indicates bits available for encoding bits of the UCS-4
character value.
UCS-4 range (hex.) UTF-8 octet sequence (binary)
0000 0000-0000 007F 0xxxxxxx
0000 0080-0000 07FF 110xxxxx 10xxxxxx
0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
Your applications don't have to handle binary at any point. Insertion is latest possible point and that's where you
convert to binary at last. Selection is earliest possible point and that's where you convert to hex, and use
hex-strings in application throughout.
When inserting, you can replace UNHEX with blob literals:
INSERT INTO table (id)
VALUES (X'434e405b823445c09cb6c359fb1b7918')
When selection, you can HEX:
SELECT HEX(id) FROM table
Expanding on Mike's answer, here's some code for encoding and decoding.
Note that the escape/unescape() functions are deprecated. If you need polyfills for them, you can check out the more comprehensive UTF-8 encoding example found here: http://jsfiddle.net/47zwb41o
// UTF-8 to hex
var utf8ToHex = function( s ){
s = unescape( encodeURIComponent( s ) );
var chr, i = 0, l = s.length, out = '';
for( ; i < l; i++ ){
chr = s.charCodeAt( i ).toString( 16 );
out += ( chr.length % 2 == 0 ) ? chr : '0' + chr;
}
return out;
};
// Hex to UTF-8
var hexToUtf8 = function( s ){
return decodeURIComponent( s.replace( /../g, '%$&' ) );
};
I want to encode some binary strings with something like base64 but only with alpha numeric chars. I know bin2hex could do this, but it makes the encoded string much longer (i tries gzcompress in the strings but didn't make much difference).
Is there any other existing encoding method to do this?
http://en.wikipedia.org/wiki/Binary-to-text_encoding
The most used forms of binary-to-text encodings are:
hexadecimal
base64
quoted-printable
uuencoding
yEnc
Ascii85
BinHex
Percent encoding