I'd like to store user id's in google analytics however since they have a policy of not allowing this, I want to encrypt some text in php and be able to decrypt when needed(The User Id).
The catch is I'd like it to be as short as possible. How can I achieve this. I'm not worried at all for this to be secure. Just need to mask it some fashion.
The simple and most seure solution to encrypting URL parameters is to not encrypt them at all. Instead use a randomly generated unique value, store it in another column in the desired database table, and select based on that.
For example:
function generateToken()
{
return strtr('+/', '-_', base64_encode(random_bytes(9)));
}
And when retrieving:
$data = $db->prepare("SELECT * FROM users WHERE selector = ?")->execute([
$_GET['user_token']
]);
Related
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.
I want to generate a Unique Code for each project being created. I have an HTML5 webpage that allows user to create new project, each project when created successfully be assigned a unique code.
I am making a Ajax call to the PHP file on the web server which in-turns saves the project details in MySql database. I have a column in the table that stores unique code for each project created.
I am confused how do i create this code ? is it in PHP or shall i do it in MySql. I want it to be a unique code which will be used by the client to distribute to their customers.
I haven't decided on the length of the key yet but it should be around 8 Digits(combination of char & int is fine ). I know i could use HashTable in Java to create this code based on the inputs from user but i am a fresher to PHP/MySql.
Any advise ?
Note: My Aim is that the key should not be repeated
You can use PHP's uniqid() to generate a unique ID. However, this should not be used for security purposes, as explicity stated in the PHP manual. For more info, go here
Example:
$unique_key = uniqid();
echo $unique_key; // Outputs unique alphanumeric key, like 5369adb278516
Generate Code:
// $length is the length of code you want to return
function generate_code($length) {
$charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789012345678900987654321234567890";
return substr(str_shuffle($charset), 0, $length);
}
To get the verification code, it will call user_code_exists() with a parameter of the generated code which is on $code = generate_code(50).
It will check the database if there's at least one row that has the same value, if the row is 0 (code doesn't exist) it will return as true.
// Do generate and verify code existence
$verification_code = "";
while($this->user_code_exists($code = generate_code(50)) == true) {
$verification_code = $code;
break;
}
public function user_code_exists($code) {
$query = $this->db->prepare("SELECT verification_code FROM accounts WHERE verification_code = :verification_code");
$query->execute(array(':verification_code' => $code));
return ($query->rowCount() == 0) ? true : false;
}
On while loop, once it returns true, the variable $verification_code holds the unique generated code.
This is just an overview, I hope this helps.
See the answers given for this question:
What is the best way to create a random hash/string?
In particular, if you want a purely random value (as opposed to, say a hash of the project name) then see the answer by #Gajus Kuizinas, except using base64_encode rather than binhex will give a shorter but still readable value:
base64_encode(mcrypt_create_iv(8, MCRYPT_DEV_URANDOM));
will give you 11 characters: NTM2OWI0YzR
Or if you don't have the mcrypt library installed, try:
base64_encode(hex2bin(uniqid()."0")); // Derived from microtime (the "0" is needed since uniqid() gives an odd number of characters
gives 10 characters: U2m5vF8FAA after discarding the trailing '=='
If you want to be paranoid about the project code never repeating, add a unique index to the column in your MySql table that stores the unique code for each project created, and repeat the number generation if your insert into the table fails.
As noted by #Mark M above, if you are concerned about security or someone masquerading an existing project code, see #Anthony Forloney's answer in the related question link above. In particular:
Numbers used once (NONCE) - They are used on requests to prevent
unauthorized access, they send a secret key and check the key each
time your code is used.
You can check out more at PHP NONCE Library from FullThrottle
Development
I needed to do something similar, a solution to keep unique id and i ended up with a solution to use PHP function time() like this $reference_number = 'BFF-' . time(); you can change the BFF to something that makes more sense to your business logic. This way i dont have to worry about if new id that is being generated was taken up before.
I hope this helps
I'm trying to send a random number to the database for a user/article ID. It is currently using auto increment as a counting system. However, I'd like for the number to be random and unpredictable.
The mt_rand() function in PHP does exactly what I need. Although, my question is what happens when the function returns a number already in use. Of course I can just use a is_null() to check. But if it keeps on picking a number in use I could imagine that that'd slow the operation down.
Any thoughts on what I might be able to do to get around this? Perhaps I'm going at this all wrong.
Also if there's a function that gives letters and numbers that would also help greatly (like Youtube's).
Thanks for reading!
Here is a simple function to create a 10 character long string. The string is built using upper/lowercase text and numbers. Auto increment is definitely the way to go, however, if you are dead set, the function below should help.
<?php
function randomID()
{
$ID = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,10);
echo $ID;
}
randomID();
?>
To make the string longer, change 10 to whatever you like. In terms of ensuring it does not already exist. I would suggest you generate the new ID and then do a search in the database to ensure it does not exist before inserting. Granted this is an extra step in the chain, but unfortunately this is what needs to be done.
Hope this helps
You should always use an auto_increment field as the primary key of your database. Not doing that costs you a great deal in performance. You can certainly create a secondary ID field with your random ID. I'd probably use a hashing function to get the best chance of a random string:
<?php $key = md5(rand(0,999).time().$myItemTitle); // ex. ce4075a3d3f6fd757eb6dd44810cbe14
You should always (in normal use cases) use an auto incremented ID for performance reasons. If you're purpose is to be able to somewhat hide the next post because someone could be guessing for it then you better add some kind of hashed unique field to your database.
Always random (just encrypting ms) :
<?php
$value = time();
$key = "543yretghf436436";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_ECB);
//if you want even long string change 128 to 256
$encrypted = base64_encode($encrypted);
$encrypted = rtrim($encrypted, '=');
echo $encrypted;
?>
e.g.
Egttu2XhRGdAiXVfszscWg
XlttfR3XaL6pym1uSNY7Kg
YvoKCweUnN8gZyodRYysLA
What you actually want is some "random" key to use as an identifier for the article. I would keep the auto_increment and eigther:
add an column with a "hashkey" or "random key" to identify the article. This poses the "i already have this key" issue (which should not be that large unless you have billions of articles). See some code examples already posted.
create an extra table with pregenerated keys (i.e. 10000 id -> key values) where you can lookup the id by key. If the table runs out you can easily generate new values. This way you don't have to worry about getting "slow" generation speed.
I often want to redirect the user or email them a link but I want to mask the parameters in the URL so they can't tell what extra information is being sent.
For example, if I want to present a link to http://www.example.com/directory/ but I also want to pass extra parameters of an email address and a hash for someone:
Email: someone#example.com
Hash: 22sd359d5823ddg4653dfgfFSG2
I can send them to this link, but I don't want them to see the parameters:
http://www.example.com/directory/someone%40example.com/22sd359d5823ddg4653dfgfFSG2
So my first thought is just to base64_encode() it, but then you get those stupid == symbols at the end for the extra bytes. And also base64 encoding also generates quite long strings.
Is there an easier, URL-friendly way to encode a string to hide its contents?
How would you normally do this? Is base64_encode() a standard practice?
You could generate a short id and store what it's suppose to do in the database. So using
http://www.example.com/directory/K2SP26
for example would store the person's email address in the database along with where they are supposed to go. Check out http://kevin.vanzonneveld.net/techblog/article/create_short_ids_with_php_like_youtube_or_tinyurl/
Using something like base64_encode(), gzcompress, etc. to encode the string isn't a good way to obfuscate it since it's trivial to decode it. And yes, another option is to store the value in the database and just pass a key as people have suggested. But assuming you don't want to bother with that, what you really should do is to actually encrypt it using a private key, and then decrypt it on the other end with the same key.
For example:
function obfuscateString($s)
{
$secretHash = "BA2EC9E717B68176902FF355C23DB6D10D421F93EAF9EE8E74C374A7B0588461";
return openssl_encrypt($s, 'AES-256-CBC', $secretHash, 0, '1234567890123456');
}
function unobfuscateString($s)
{
$secretHash = "BA2EC9E717B68176902FF355C23DB6D10D421F93EAF9EE8E74C374A7B0588461";
return openssl_decrypt($s, 'AES-256-CBC', $secretHash, 0, '1234567890123456');
}
(Requires PHP version >= 5.3.0.) Replace the $secretHash with your own secret hex string.
Note: The initialization vector ('1234567890123456') is just a filler string in this example, but that's ok. You could come up with a way to use a unique initialization vector, but it isn't important for the purposes of obfuscating the URL parameters in most cases.
Probably a silly answer but why not use the mcrypt functions to hide your parameters from at least the more casual users?
If your redirect is triggered by PHP, I suppose storing the data in a session would be the obvious choice.
<?php
function redirectTo($url, $data) {
session_start();
$hash = md5(uniqid("rediredt", true));
$_SESSION[$hash] = array(
'my' => 'data',
'is' => 'invisible',
'to' => 'the user',
);
$delim = strpos($url, '?') ? '&' : '?';
$url .= $delim . 'redirection-key=' . $hash;
// might want to send 301 / 302 header…
header('Location: ' . $url);
exit; // might want to avoid exit if you're running fcgid or similar
}
function isRedirected() {
if (empty($_GET['redirection-key'])) {
return null;
}
if (!isset($_SESSION[$_GET['redirection-key']])) {
return array();
}
$t = $_SESSION[$_GET['redirection-key']];
unset($_SESSION[$_GET['redirection-key']]);
return $t;
}
might help you grasp the idea…
You have one of two choices:
The email address is hashed, and can therefore be decoded by a savy user.
-or-
The email address is stored on your server (database) and the email link contains only the database primary ID.
If you want the most secure method, that also gives the prettiest URLs, use method 2. If you absolutely do not want to store the email address in your database, then either use a common hash, such as base64 or even rot13, or roll your own. You will find that rolling your own is not simply, but it will stop most casual users from trying to peek inside the hash.
Its a bit hacky, but if you send them a page containing:
<form id="getme" action="directory/someone" method="POST">
<input type="hidden" name="email" value="someone#example.com">
</form>
<script> document.getElementById("getme").sumbit();</script>
As soon as that loads (assuming they have javascript enabled), they will be redirected where you want them with no url dirtyness.
I have an email address and I want to create a unique ID based on it, so say email is me#email.com that turns into 66wyy7eu
Ive found a close solution http://www.php.net/manual/en/function.uniqid.php#96898 but it needs the input to be numeric
emails are already unique.
You can't guarantee that a hash of the email will always be unique either.
If your using a DB. an auto-increment field will be unique
Check out hash(). This should allow you to generate a sufficiently unique ID based on a string input.
have you read about md5 ?
PHP md5 function
Personally, I would use something like md5() or sha1(). PHP does have a hash() function that allows you to specify the algorithm used: http://php.net/manual/en/function.hash.php
Please see my answer to another question that is of the same nature, the function can be modified accordingly to suite your needs:
PHP random URL names (short URL)
as stated above the email addresses are unique, and if you store them into a database you will get a unique identification number from the Auto-increment column.
With that id you can then use the above function to create a unique hash for that id, and store that in the same row, then you have 2 identifiers for your email address, the ID to use internally and the encrypted key to use as a short URL service.
alternatively there is a simpler approach where as you constantly create random string and then check to see if it is within your database, if the key is within your database then you generate another and check again until you have a unique id.
here's a quick example:
function createRandomID($length = 9)
{
$random = '';
for ($i = 0; $i < $length; $i++)
{
$random .= chr(rand(ord('a'), ord('z')));
}
return $random;
}
and then simply do:
do
{
$id = createRandomID();
}while(!idExists($id));
//Insert $id into our DB along with the email!
Note: The limitations of the characters effects the amount of unique strings it can produce, the more strings you have within your database the higher the loop rate becomes which could increase the load on your DB and result in slower pages for the user.