php encode string and vice-versa - php

I have some entities(objects), each one having an id(unique) and a name.
When i want to display oneof these , i have a url like www.domain.com/view/key:xxx.
The key is just the id of the entity encoded with base64_encode, so it's not straightforward from the url what the id is.
What i'm trying to do now (due to the projects specifications) is have the key contain only numbers and letters (base64_encode provides a result like eyJpZCI6IjM2In0= or eyJpZCI6IjM2In0%3D after url encode).
Is there a simple alternative to this? It's not a high-security issue - there are many ways the id can be revealed -, i just need to have a key that contains only letters and numbers that is produced by the entity ID (maybe in combination with its name) that can be decoded to give me the ID back.
All different encode methods i've found can contain special characters as well.
Any help here?
Thanks in advance

This answer doesn't really apply encryption, but since your question was tagged with encoding as well ...
Since PHP 5 you can use bin2hex:
$s = base64_decode('eyJpZCI6IjM2In0=');
echo bin2hex($s);
Output:
7b226964223a223336227d
To decode:
$s = hex2bin($data);
Or:
$s = pack('H*', $data);
Btw, if the id is sensitive you might want to consider tamper proofing it as an alternative to full-blown encryption.
Forgot to mention how you can make base64 encoded data URL safe:
function base64_url_encode($input)
{
return strtr(base64_encode($input), '+/=', '-_,');
}
function base64_url_decode($input)
{
return base64_decode(strtr($input, '-_,', '+/='));
}

There are many PHP encoding/decoding functions.
You can find a lot here and here.
Alternatively just get rid of the = at the end of the base64_encode and add it in the PHP code for base64_decode to find the ID.

Related

Encrypted values (mcrypt_encrypt) in URL parameters generating different results while requesting.How to tackle the situation?

I am using the following function to encrypt a string ($str) using a key ($key) to make a unique key.
Sample Code:
<?php
$key = "####";
$str = "123456789";
$encrypted_key = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $str, MCRYPT_MODE_CBC, md5(md5($key))));
echo $encrypted_key; // 3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw+6WAns=
?>
The function is returning values consisting special characters including '+' . I am storing this values in database as a unique ID.
However in certain conditions, I need to pass the $encrypted_key through URLs . i.e; for using it with RESFful web services
Sample URL:
www.example.com/index.php?encrypted_key=3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw+6WAns=
But this when requested through URL will decode '+' into 'spaces'
Code:
echo $encrypted_key = $_REQUEST['encrypted_key'];
// 3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw 6WAns=
This conversion is further affecting the DB checks :
'3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw 6WAns=' against '3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw+6WAns='
Also I am having a concern of storing these encrypted values into indexed MySQL DB columns.
What should be the best practice to be adopted here? Any advise will be highly appreciated.
This answer only addresses the representation, not the likely-to-be-wrong use of crypto.
When you build objects that have special representation rules like database queries, paths in URLs, HTML code, JS code, and so on, you must ensure that you perform the proper kind of encoding of the values so that they roundtrip without harm.
For database query parameters, do not use string concatenation. Use prepared statements and placeholders.
For URLs, use the proper URL encoding function or an URL builder to construct your URL, do not blindly concatenate strings.
First, is not a good idea to use encrypted values as Unique ID or as Conditional Field, because they will change for the same value. This is very commom in encryption. If an encryption algorithm don't change the result for the same entry, it is not a good encryption.
Second, I had the same problem to deal with encryption and URL, and in my case a made my own encryption algorithm, using only valid characters for URL.
It is not dificult to implement an encryption: I used the ASCII code, one simple key, one simple math function, and nothing more. To decryption, I "reversed" the math function.

Removing these extra characters

I'm working on an application and I'm stuck here.
I'm making a product delete page, where the id is passed in the URL so that I can search the database and select the particular record.
Since passing the id naked is not a good idea, so therefore I'm encrypting the id in a hash and then passing. But since the hash have some spaces in between, when I try to use it in my application..extra space characters are added in the hash to fill in the spaces.
Here's my encrypt function :-
function getHash($recordid)
{
global $db;
$key_value="12466X##";
$plain_text=$recordid;
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT);
return $encrypted_text;
}
Here's what I get output for $plain_text = 1 when I do not pass in the URL and simply print it.
ÑÛo‡Ó‰-7
But, if I pass it via URL, it gets converted to this :-
%D1%DBo%87%D3%89-7
Therefore surely I wouldn't get the correct results when I decrypt it.
Is there any way I can get the original value after decrypting it (1 in this example), or could I entirely use a different decrypt, encrypt function so that I get rid of this problem?
Thank you.
Since these are all 8-bit characters, when they get encoded, they're converted to their %XX Hex representation. The web server does the reverse for you when it's in the Query part of the URL, so you should be ok. Still, it's safer to base64-encode the crypted string before making an URL of it, and base64-decode it when you get it back, so you need to deal with ascii characters only.

Validate a string using pack('H*')

I'm working on an encrypted database... I have been using m_crypt functions.. I have sucessfully got my method of encryption/decryption.. But a problem lies with creating my OO class to serve this function.. I have the following:
class Encryption {
public function __construct($Hex = null){
if (isset($Hex)){
if (ctype_xdigit($Hex)){
echo "Is Hex";
}
if (preg_match('~^[01]+$~', $Hex)) {
echo "Is Binary";
}
}
}
}
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
$Class_OO = new Encryption($key);
The echos are for testing purposes.. But I want to validate this as a valid hexidecimal/binary or the datatype this string is.
performing:
print_r($key);
Returns the following:
¼°K~:صGcï¼U«à)ýë®^A~/û*£
But what datatype is this? On the documentation: http://www.php.net/manual/en/function.mcrypt-encrypt.php The line is presented:
convert a string into a key
key is specified using hexadecimal
So my question is what datatype is this? I understand this is in the ASCII range, but that is as far as my knowledge goes.. Furthermore, a successful answer for this will also assist me in creating another key which is not the one specified by the actual documentation
Your $key is the return value from pack, which in this case is a binary string (essentially raw binary values). See the first line in the documentation for the pack() function return value: http://php.net/manual/en/function.pack.php
Pack given arguments into binary string [emphasis added] according to format.
You would normally base64 encode a binary string before attempting any kind of output, because by definition, a binary string may (and often does) include non-printable characters, or worse - terminal control/escape sequences which can hose up your screen.
Think of it like printing a raw Word or Excel file: you'll probably see recognizable values (although in this case occasional alpha-numerics), but lots of garbage too.
Base64 encoding is a technique to inspect these strings in a safe way.
But what your question implies is that you are very much entering this territory new. You should probably take a look at the Matasano crypto tutorial here: http://www.matasano.com/articles/crypto-challenges/. It is an excellent starting point, and completing exercise #1 in it (maybe 20 minutes of work) will shed complete light on your question above.
In response to your question.. The only viable viable datatype this is submitted in is a string. As you said in your comment:
I have figured using the IV functions of mcrypt then using bin2hex,
using this in the second param of the pack function seems to work
without a fail.. BUT, my overall question is how to validate:
¼°K~:صGcï¼U«à)ýë®^A~/û*£ down to a specific datatype
You have answered how to create an acceptable format for the pack('H*') but as far as validation goes:
if (is_string($Var)){
}
Is the way to go, as this is how it's submitted. It's not a bool, hex, binary, int.. So the only valid method of validating is to validate it as a string.

PHP URL Shortening Algorithm

Could anyone recommend a preferred algorithm to use for URL shortening? I'm coding using PHP. Initially I thought about writing something that would start at a character such as "a" and iterate through requests, creating records in a database and therefore having to increment the character to b, c, d ... A, B and so on as appropriate.
However it dawned on me that this algorithm could be pretty heavy/clumsy and there could be a better way to do it.
I read around a bit on Google and some people seem to be doing it with base conversion from the database's ID column. This isn't something I'm too familiar with.
Could someone elaborate and explain to me how this would work? A couple of code examples would be great, too.
I obviously don't want a complete solution as I would like to learn by doing it myself, but just an explanation/pseudo-code on how this would work would be excellent.
Most shortening services just use a counter that is incremented with every entry and convert the base from 10 to 64.
An implementation in PHP could look like this:
function encode($number) {
return strtr(rtrim(base64_encode(pack('i', $number)), '='), '+/', '-_');
}
function decode($base64) {
$number = unpack('i', base64_decode(str_pad(strtr($base64, '-_', '+/'), strlen($base64) % 4, '=')));
return $number[1];
}
$number = mt_rand(0, PHP_INT_MAX);
var_dump(decode(encode($number)) === $number);
The encode function takes an integer number, converts it into bytes (pack), encodes it with the Base-64 encoding (base64_encode), trims the trailing padding = (rtrim), and replaces the characters + and / by - and _ respectively (strtr). The decode function is the inverse function to encode and does the exact opposite (except adding trailing padding).
The additional use of strtr is to translate the original Base-64 alphabet to the URL and filename safe alphabet as + and / need to be encoded with the Percentage-encoding.
You can use base_convert function to do a base convertion from 10 to 36 with the database IDs.
<?php
$id = 315;
echo base_convert($id, 10, 36), "\n";
?>
Or you can reuse some of the ideas presented in the comments on the page bellow:
http://php.net/manual/en/function.base-convert.php
Assuming your PRIMARY KEY is an INT and it auto_increments, the following code will get you going =).
<?php
$inSQL = "INSERT INTO short_urls() VALUES();";
$inResult = mysql_query($inSQL);
$databaseID = base_convert(mysql_insert_id(), 10, 36);
// $databaseID is now your short URL
?>
EDIT: Included the base_convert from HGF's answer. I forgot to base_convert in the original post.
i used to break ID by algorithm similar with how to convert from decimal to hex, but it will use 62 character instead of 16 character that hex would use.
'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
example : if you will change ID = 1234567890 you will get kv7yl1 as your a key.
I adopted a "light" solution. On user request I generate a unique identifier (checking for conflicts in db) with this python snipplet:
url_hash = base64.b64encode(os.urandom(int(math.ceil(0.75*7))))[:6]
and store it in db.
The native PHP base_convert() works well for small ranges of numbers, but if you really need to encode large values, consider using something like the implementation provided here which will work to base 64 and beyond if you simply provide more legal characters for the encoding.
http://af-design.com/blog/2010/08/10/working-with-big-integers-in-php/
Here try this method :
hash_hmac('joaat', "http://www.example.com/long/url/", "secretkey");
It will provide you with hash value fit for a professional url shortener, e.g: '142ecd53'

obfuscate or encrypt some plain text data in PHP

I need to obfuscate or encrypt some plain text data in my php 5.2 application.
I'd prefer a solution that would have input string and output string retain the same length.
This does not need to extremely strong, as there are numerous other layers of security in place. Strong would be good, but this will just keep programmers/dba/support people/etc from accidentally reading the text from within the database.
key considerations
EDIT ADD I'd prefer a solution that would have input string and output string retain the same length.
only string text will be obfuscated/encrypted for storage in a database
the php application will need to obfuscate/encrypt the data before the database save and will need to un-obfuscate/dencrypt following the database read
this is a modification to an existing application
only some columns will need to be obfuscated/encrypted
only some rows will need to be obfuscated/encrypted, based on a Type field
there are only a few load/save points to handle
max column size is already determined for some fields, but not for others, but I'd prefer a solution to work within the existing size of the restricted fields
EDIT, ADD the key will be probably be a composite of some Primary key info +uneditable fields
here is a sample database table and data:
int char(1) varchar(24) int date
MyPrimaryKey RowType UserText UserNo DateChange
------------ ------- ------------------------ -------- ----------------
1 N nothing special here 43 6/20/2009 12:11am
2 N same thing, wow! 78 6/23/2009 1:03pm
3 S fBJKg}.jkjWfF78dlg#45kjg 43 6/25/2009 6:45am
4 N same old, same old text 21 6/25/2009 8:11am
The application would load and display rows 1,2, and 4 normally. However it would conditionally (based on row type) handle the text in row 3 using this obfuscate/encrypt and un-obfuscate/decrypt logic.
Can anyone provide obfuscate/encrypt and un-obfuscate/decrypt functions code, links, and or pointer that would help here?
thanks!
EDIT
I like the simple base64 encoding idea, but is there a method that can keep the data within a fixed size. All methods listed so far have the output value larger than the input value. This will be a problem for some columns, where the user can enter in 50 characters and it is stored in a varchar(50) column.
for simple obfuscation use strtr() - Translate certain characters:
string strtr ( string $str , string $from , string $to )
to encode in php:
$readable='This is a special test string ABC123 ([+,-!#$%&*])';
$unreadable=strtr($readable,' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'
,'¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ '
);
print $unreadable; //outputs: "ÕéêôAêôAâAôñæäêâíAõæôõAôõóêïèAÂÃIJ³´A©Ü¬­®¢¤¥¦§«Þª"
to decode in php:
$unreadable='ÕéêôAêôAâAôñæäêâíAõæôõAôõóêïèAÂÃIJ³´A©Ü¬­®¢¤¥¦§«Þª';
$readable=strtr($unreadable,'¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ '
,' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'
);
print $readable; //outputs: "This is a special test string ABC123 ([+,-!#$%&*])"
you can easily replicate this logic in the DB if necessary (without looping): Using a Table of Numbers, by Erland Sommarskog
How about base64 encoding? We use to use that to make SMS messages in our SMS Gateway DB unreadable by the developers.
Try these PHP functions convert_uuencode and convert_uudecode:
function encrypt_decrypt ($data, $encrypt) {
if ($encrypt == true) {
$output = base64_encode (convert_uuencode ($data));
} else {
$output = convert_uudecode (base64_decode ($data));
}
return $output;
}
$enc_txt = encrypt_decrypt ("HELLO DATA", true);
echo $enc_txt."\n"; // KjIkNSwzJFxAMSQlNDAwYGAKYAo=
echo encrypt_decrypt ($enc_txt, false); // HELLO DATA
There are a few options.
If you want very strong, you could look into mcrypt.
But if it's only so working developers cant read the text without some work to actually do it. Then you could just BASE64 encode it or uuencode it
If you have mcrypt installed (all my current PHP environments have), you could use mcrypt_encrypt and mcrypt_decrypt like this:
function encrypt ($text) {
global $key;
return mcrypt_encrypt (MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, "abcdefghijklmnopqrstuvwxyz012345");
}
function decrypt ($secret) {
global $key;
return rtrim (mcrypt_decrypt (MCRYPT_RIJNDAEL_256, $key, $secret, MCRYPT_MODE_ECB, "abcdefghijklmnopqrstuvwxyz012345"), "\0");
}
which uses a global $key and AES (very strong).
Drawbacks are performance (in comparison to simpler ones like Base64) and that you somehow have to fix a key.
Cheers,
if you're using mysql around version 5, then you don't even need much php for it, you can do it inside your query with the mysql string functions encrypt(text, password) and decrypt(text, password)
http://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html
DECODE(crypt_str,pass_str)
Decrypts the encrypted string crypt_str using pass_str as the password. crypt_str should be a string returned from ENCODE().
ENCODE(str,pass_str)
Encrypt str using pass_str as the password. To decrypt the result, use DECODE().
The result is a binary string of the same length as str.
The strength of the encryption is based on how good the random generator is. It should suffice for short strings.
update: another possibility would be rot13 ^^
Try using the mcrypt library. It's not included with standard PHP, but it's easily downloadable and very commonly used. Here's a quick tutorial on what you can do with it.
It's best to make sure the key you use for the encryption is stored in a secure place, but if you aren't really concerned about security, you'd probably be OK just hardcoding the key into your code somewhere.

Categories