This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a string to number and back to string?
I have a string that looks like:
AhgRtlK==
and I need to be able to encrypt and decrypt this string into numbers that might look like this:
1275653444
It's like phone charge credit (some thing like that)
EDIT :
i want to create some thing like mobile charge credit that contains value of credit card
but encrypted
I don't think you understand the problem well enough to ask the right question. To the extent I understand what you're saying, it's not well thought out. Suppose some code meant a credit of $500. Well, it would always mean that, today, tomorrow, and forever, even after I spent some of it.
So you don't want codes that decrypt to values. You want codes that identify unique accounts that have balances. (There are great algorithms to do that, and they're generally based on HMACs.)
You can just use the ascii value to convert a string into a number:
$integer = '';
foreach (str_split($string) as $char) {
$integer .= sprintf("%03s", ord($char));
}
return $integer;
To convert it back you can use this:
$string = '';
foreach (str_split($integer, 3) as $number) {
$string .= chr($number);
}
return $string;
Related
I want to convert a text to number using any two way encryption function in PHP ..
So that if I'm converting a text or string into a random encrypted number , again I can convert back it to string ...
Please help me..
I have also used crc32 function but that is one way hashing ...so I want a two way hashing function..
Please help me
From your question it seems you does not know what encryption is. To make its algorithm you have to know first what it is
I recommend to learn some basic cyphers to make your own, an easy one is ADFGVX; search the internet and try to understand how it works.
Your question is indeed a first step in encryption, but it is totally up to you that how you convert the input text to number, you can call A=1, B=2, C=4 or A=65, B=66 which are ASCI equals of alphabets or even you can make your own list to change characters to numbers
Second step is to shuffle the numbers in such a way that only you can unshuffled them but without knowing how to do that others should not be able to do that or may find it very difficult to do that.
Then there is a concept of key or password. Some cyphers encrypt the input using a key and the decryption can only be done using that key, if one doesn’t know the key it would be very difficult or impossible to decrypt it.
Internationally there are many cyphers some of them are considered week which means that without knowing the key they can be decrypted easily and some are strong which means decryption is very difficult, in answers to you question you have read the name AES, this is a names a standard cypher. You can find built-in functions for many cyphers in different programming languages.
This is just an introduction; there are many topics that can be discussed but it is up to you how much you want to learn
Now for the answer to your question
You can start building your cypher using the below code.
$encrypted_text = encrypt("abcd");
$decrypted_text = decrypt($encrypted_text);
var_dump($decrypted_text);
function encrypt($input_str){
$output_str = "";
$charachters = str_split($input_str);
for($i = 0 ; $i < sizeof($charachters) ; $i++){
$output_str .= str_pad(ord($charachters[$i]), 3, "0", STR_PAD_LEFT);
}
return $output_str;
}
function decrypt($input_str){
$output_str = "";
$charachters = str_split($input_str,3);
for($i = 0 ; $i < sizeof($charachters) ; $i++){
$output_str .= chr($charachters[$i]);
}
return $output_str;
}
You can use the following code to get a number equivalent to a ski code
<?php
$A=ord("H");
echo($A);
?>
result = 72
I am using a system to sell tickets for a game.
Current id numbers for tickets are consecutive. EG: 651,652,653. If someone would buy a new ticket, his ticket id would be 654.
I am looking for a solution to inform the user about his ticket unique id by sending him a string instead of the ticket number, so that he can have a reference, but he would not know how many tickets were purchased before.
By encrypting ticket number 651 I want to generate a string having 6-7 characters maximum, all uppercase, and this algorithm should be two way and reversed only using a secret key.
EG: using a key like 881hu and encrypting number 651 I should obtain something like UTR8N1A0 .
I want uppercase letters for readability, and the length of the new string should not be too long, because then it would be hard to remember.
Do I have any options of such algorithm? I am using PHP as server language for all this.
I agree with #RaggaMuffin-420 comment, that way you can have 6-7 uppercase characters maximum. As for something like mcrypt there's no easy way to make it in 6-7 chars...
of course if you don't want to do something silly like:
$secret = 123456789;
$tickedID = 654;
$code = strtoupper( dechex($secret + $tickedID) );
echo 'Code is: ' . $code . '<br>';
$decode = hexdec($code) - $secret;
echo 'Decoded: ' . $decode;
Output:
Code is: 75BCFA3
Decoded: 654
Disclaimer: I would go with adding unique code in database referencing to the actual ticked id.
One option - you can calculate a hash(consecutive_number + salt) and then encode the hash.
Update: If you need to quickly extract the original consecutive_number, hide it inside the encoded hash string. You can read it, and you can verify it by re-calculating the hash (as the salt is secret, one won't be able to easily calculate the hash to construct a valid key).
There's a lot of bad advice floating around the Internet (and bad designs like "hashids"), but ultimately what you want is:
Don't do this:
Do this instead:
Images (and detailed arguments) from: The Comprehensive Guide to URL Parameter Encryption in PHP
I have written a function to generate a random string of 7 alphanumeric characters which I am then inserting in a mysql database.
Here is the code :
function getRandomID(){
$tmp ="";
$characters=array("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","1","2","3","4","5","6","7","8","9");
for($i=0;$i<7;$i++)
$tmp.=$characters[rand(0,count($characters)-1)];
return $tmp;
}
I am not checking for duplicates atm because I anticipate there will be no more than 1000 entries in the database and I've calculated that this function can return (35)^7 = 64,339,296,875 possible values.
I am testing it out locally as well as on a live server.
The problem is just in the last hour , this function generated duplicate values twice.
I came upon 3 entries in the database all of which had the same random string.
I do not know what could have caused this as I tried numerous times afterwards and the problem wasn't reproducible.
Does anybody have any idea what could be going on here?
Many thanks in advance
Designing your code with the mindset of "meh, that's not going to happen" is a very risky game, just do it properly once so you don't have to get back to your code multiple times to quick-fix minor things like these.
Do the duplicate check and you'll be solid.
You can create a function like
function stringExists($string)
{
...
return $boolValue;
}
And you can easily create a while loop that generates a new string while an old one has been generated.
$duplicate = true;
while($duplicate)
{
$newString = getRandomId();
$duplicate = !stringExists($string);
}
// Work with the newest string that is not a duplicate.
If you really want to get into it
You can then take a look at the documentation for rand if you want to find out what might be causing your problem. Besides, 3 entries doesn't mean anything if we don't know how many total entries there are. Also sometimes "random" function are not as random as one might think, sometimes random functions in some programming languages are always usable but require some sort of an initiation before they become "truly" random.
The time of the inserts might also be a part of the problem, there are plenty of threads on the internet, like this one on stackoverflow, that have some interesting points that can affect your "random"ness.
Whether it's true or not, not which has been pointed out in the comment, you can be pretty sure to find an answer to your question in related threads and topics.
Short answer: Don't think about it and do a duplicate check, it's easy.
Note that you should, of-course, make your ID be a UNIQUE constraint in the database to begin with.
Random != unique. Collisions happen. Check that the value is unique before you insert into the database, and/or put an integrity contstraint in your DB to enforce uniqueness.
If you're using a very old version of PHP [eg. pre-4.2] you have to seed the random number generator with srand().
Aside from #2, it's probably not your getRandomID() function but something else in your code that's re-using previous values.
If you need to enrer unique data in the DB, you may use PHP function uniqid(). (http://ca3.php.net/uniqid)
The function generates more-less random string based on current microseconds. So in theory it is unique.
But still, its always good to check before insert. Or at least put UNIQUE index on the field.
You could do something like this:
function randomString($length, $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
$string = "";
$charsLength = strlen($chars);
for ($i = 0; $i < intval($length); $i++) {
$string .= $chars[rand(0, $charsLength - 1)];
}
return $string;
}
The function above will generate a random string in the given length from the given characters. This makes it a little bit more flexible, than your implementation, if you need to use it in amother context later.
Then you could do a check like this:
$id = null;
do {
$id = randomString(7);
} while (!isUnique($id));
// do your insert here. You need to write your isUnique, so that it checks if
// the given string is unique or not.
This question already has answers here:
How to remove all leading zeroes in a string
(11 answers)
Closed 9 years ago.
I am posting this as this isn't something most newbies may be familiar with.
The Problem
We have a ticketing system which makes use of a numeric id. Now some people in the company prefer to pre-pend zeroes to the ticket number and some people would reference it without the leading zeroes which is the correct way. So to standardize the output we have to remove the leading zeroes.
This may sound simple to do, but we can't merely run a str_replace over it as this may remove valid 0's in the middle of the number.
Now you could preg match and do all sorts of funky things to find the answer, but the simplest is to merely cast the numeric string to an int.
Let's user the following as an example:
<?php
$correct = 45678;
$incorrect = 0045678;
echo $correct . '<br />';
echo $incorrect;
?>
And you should get the following printed out:
45678
0045678
Now essentially these are the same for the application, but I would like to be able to cater for people entering the information in the incorrect format.
Using ltrim:
$str="0045678";
$str = ltrim($str, '0');
echo $str;
you can also use ltrim() http://de3.php.net/manual/en/function.ltrim.php this removes the desired char from the left
Simplest Solution
As they say the simplest solution is often the best. And what is easier than telling PHP that this is an integer we are working with. We do this by pre-pending (int) to tell PHP that we are working with an integer.
Using the previous example:
<?php
$correct = 45678;
$incorrect = (int)0045678;
echo $correct . '<br />';
echo $incorrect;
?>
And you should get the following printed out:
45678
45678
I know it seems self explanatory, but I only learnt about type casting a couple of years into website development. Maybe you will find this of use.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am wondering what other approaches you would take to do some simple string splitting in PHP. I am receiving a response from a SMS gateway where two of the interesting values are the code used and the users text message.
The code could be something like: Freetrip (lowercase, uppercase, mixed case)
The user message should in the best case scenario be e.g. like: Freetrip 12345 ($code "space" XXXXX).
Each X should be a digit between 1 and 5. Any other value/character should return an error. So the regex would be simplified as: chars=5 where each digit >=1 and <=5.
What I need to store at the end would be each of the 5 digits values.
My simplest approach would be to lowercase the entire message string and subtract the also lowercased code (plus the space) from the message string. That would leave me with the 5 digits which I would then split into 5 unique variables to store in the DB.
Now the tricky part is that the best case scenario described above may be hard to achieve. Typing a SMS is fiddly and typing errors occur easily. Some errors that may occur are the following:
Too few or many digits.
Non-digits characters.
More characters after the XXXXX combination.
Probably some other cases.
Any of those should return an individual error message which I can return to the sender.
if (!preg_match('/^freetrip\s+([1-5]{5})$/i', $sms, $matches)) exit("error");
print_r($matches);
I had some experience with SMS-platforms and AFAIK one error is enough. We tried to detect similar characters like small L and big I etc, or zero and O-letter. For example in your case you could write something like this:
preg_match('/^freetr[il1|]p\s+([1-5]{5})$/i', $sms, $matches);
the same you can do in any place of message pattern (if you want).
I did something like this (not sure - it was 5 years ago):
if (!preg_match('/^(\w+)\s+(.*)/i', $sms, $matches)) exit('bad message format');
$value = $matches[2];
// some letters look like digits
$value = str_replace(array('o', 'O'), 0);
$value = str_replace(array('i', 'I', 'l'), 1);
if (!preg_match('/^[12345]{5}/')) exit("invalid code");
// do something here... message is OK.
Sure in this case you can check "freetrip" or not, value is [1-5]{5} or not etc, and response your error as much as allows your imagination :). Good luck.
EDIT: The last one is updated and should fit your case. It's better, because it will be very simple to create another service on it's example if you'll need it.
You could do something like that:
$code = 'Freetrip';
if (strlen($input) <= strlen($code)) {
// too short
} elseif (!preg_match('/^'.preg_quote($code, '/').'(.*)/i', $input, $match)) {
// wrong code
} else {
$x = (int)trim($match[0]);
if ($x < 11111) {
// too small
} elseif ($x > 55555) {
// too large
} else {
// valid
}
}