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.
Related
I am currently working on a new PHP site for a site currently utilizing ColdFusion 10. When the new site is ready the ColdFusion site will be decommissioned and I won't have access to anything related to ColdFusion. I don't want to have to reset all the previous passwords so need to be able to duplicate the one-way SHA-512 hash that is utilized in ColdFusion in PHP.
This question on Stack Overflow is very relevant to this problem:
hash function that works identically on ColdFusion MX7 and PHP 5.x?
The difference is they manually looped in 1024 iterations in ColdFusion. The ColdFusion site I am translating uses the built in iterations feature. I have tried what they did in the above question, plus a few variations including XOR in the end but ultimately I can't find documentation on what ColdFusion is doing during those iterations.
ColdFusion:
<cfset hpswd = Hash(FORM.npswd & salt, "SHA-512", "UTF-8", 1000) >
PHP (without iterations logic):
$hpswd = strtoupper(hash("sha512", $npswd.$salt));
Given this password: q7+Z6Wp#&#hQ
With this salt: F4DD573A-EC09-0A78-61B5DA6CBDB39F36
ColdFusion gives this Hash (with 1000 iterations): 1FA341B135918B61CB165AA67B33D024CC8243C679F20967A690C159D1A48FACFA4C57C33DDDE3D64539BF4211C44C8D1B18C787917CD779B2777856438E4D21
Even with making sure to strtoupper with PHP I have not managed to duplicate the iterations step so the question, what operands is ColdFusion 10+ doing during the iterations step?
Regardless of language, a SHA-512 hashing function should return the same output given the same inputs. Here, it looks like you may just need to ensure that your inputs are the same. This includes the encoding of the text you are inputting. Then you'll hash over it the same total number of times.
As of today, the CFDocs documentation of ColdFusion hash() is incorrect, but I have submitted a correction for that. See my comments above about why I believe Adobe lists their defaults this way. A Default of 1 Iteration is correct for Lucee CFML, but not for Adobe CF. You are correct that the ACF default is 0. CF2018 clarifies this parameter.
Now, to your issue, your original code in ACF10 is:
<cfset hpswd = Hash(FORM.npswd & salt, "SHA-512", "UTF-8", 1000) >
This says that you are hashing with the SHA-512 algorithm, using UTF-8 encoding, and repeating an additional 1000 times. This means that your hash() function is actually being called 1001 times for your final output.
So:
<cfset npswd="q7+Z6Wp#&##hQ">
<cfset salt = "F4DD573A-EC09-0A78-61B5DA6CBDB39F36">
<cfset hpswd = Hash(npswd & salt, "SHA-512","UTF-8",1000) >
<cfoutput>#hpswd#</cfoutput>
Gives us 1FA341B135918B61CB165AA67B33D024CC8243C679F20967A690C159D1A48FACFA4C57C33DDDE3D64539BF4211C44C8D1B18C787917CD779B2777856438E4D21.
https://trycf.com/gist/7212b3ee118664c5a7f1fb744b30212d/acf?theme=monokai
One thing to note is that the ColdFusion hash() function returns a HEXIDECIMAL string of the hashed input, but when it uses it's iteration argument, it iterates over the BINARY output of the hashed value. This will make a big difference in the final output.
https://trycf.com/gist/c879e9e900e8fd0aa23e766bc308e072/acf?theme=monokai
To do this in PHP, we'd do something like this:
NOTE: I am not a PHP developer, so this is probably not the best way to do this. Don't judge me, please. :-)
<?php
mb_internal_encoding("UTF-8");
$npswd="q7+Z6Wp#&#hQ";
$salt = "F4DD573A-EC09-0A78-61B5DA6CBDB39F36";
$hpswd = $npswd.$salt ;
for($i=1; $i<=1001; $i++){
$hpswd = hash("SHA512",$hpswd,true); // raw_output=true argument >> raw binary data.
// > https://www.php.net/manual/en/function.hash.php
}
echo(strtoupper(bin2hex($hpswd)));
?>
The first thing I do is ensure that the encoding we are using is UTF-8. Then I iterate over the given input string 1+1000 times. Using the raw_output argument of PHP hash() gives us binary representations each loop, which will give us the same final output. Afterwards, we use bin2hex() to convert the final binary value to a hexidecimal value, and then strtoupper() to uppercase it. Giving us 1FA341B135918B61CB165AA67B33D024CC8243C679F20967A690C159D1A48FACFA4C57C33DDDE3D64539BF4211C44C8D1B18C787917CD779B2777856438E4D21, matching the CF-hashed value.
Also note that CF returns an uppercase value whereas PHP is lowercase.
And final note: There are better methods for storing and using hashed passwords in PHP. This will help convert between CF and PHP hashes, but it would probably be better to ultimately convert all stored hashes into the PHP equivalents. https://www.php.net/manual/en/faq.passwords.php
=============================================================
A point of clarification:
Both Adobe and Lucee changed the name of this parameter to clarify their intent, however they behave differently.
Lucee named the parameter numIterations with default 1. This is the total times that hash() will run.
In CF2018, with the introduction of Named Parameters, Adobe renamed the parameter additionalIterations from the original (and still documented) iterations. The original improper parameter name didn't matter prior to CF2018 because you couldn't use named params anyway. On their hash() documentation page, their verbiage is "Hence, this parameter is the number of iterations + 1. The default number of additional iterations is 0." (emphasis mine) The behavior has always (since CF10) matched this description, but there is clearly some confusion about its actual meaning, especially since there is a difference with Lucee's behavior and with Adobe's incorrect initial name of the parameter.
The parameter name iterations is incorrect and doesn't work with either Adobe CF 2018 or Lucee 4.5 or 5.x. And this is a function that is not currently compatible as-is between Lucee and Adobe ColdFusion.
The important thing to remember, especially if working with both Adobe and Lucee code, is that this function with the ???Iterations named param specified will produce two different outputs if the same-ish code is run. Adobe will run a hash() one additional time vs Lucee. The good news is that since the param names aren't the same, then if they are used, an error will be thrown instead of silently producing different hashes.
hash("Stack Overflow","md5","UTF-8",42) ;
// Lucee: C0F20A4219490E4BF9F03ED51A546F27
// Adobe: 42C57ECBF9FF2B4BEC61010B7807165A
hash(input="Stack Overflow", algorithm="MD5", encoding="UTF-8", numIterations=42) ;
// Lucee: C0F20A4219490E4BF9F03ED51A546F27
// Adobe: Error: Parameter validation error
hash(string="Stack Overflow", algorithm="MD5", encoding="UTF-8", additionalIterations=42) ;
// Lucee: Error: argument [ADDITIONALITERATIONS] is not allowed
// Adobe: 42C57ECBF9FF2B4BEC61010B7807165A
https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-h-im/hash.html
https://docs.lucee.org/reference/functions/hash.html
See https://cfdocs.org/hash "...in Adobe CF the value is the number of additional iterations."
So I am working with this API and using Laravel, and I am trying to build an auth string. This is the documentation I was given, but I am having a little trouble as this is something relatively new to me.
Here are the auth instructions:
The authentication parameter is a string and it can calculated by the
caller or the caller can choose to save this value as a parameter
together with connection ID and API key.
The authentication is a base64 string of a HMAC SHA1 hash. This is
computed by using the binary of API Key in in
########################## format in all lower case and UTF8 encoding as the key and computer HMAC SHA1 hash on the binary of
Connection ID in ################################ format in all lower
case and UTF8 encoding.
The result binary hash is then base64 encoded and the text result is
what should be passed as the authentication parameter. In C# the code
to calculate the authentication may look like:
HMACSHA1 hmac = new HMACSHA1(
UTF8Encoding.UTF8.GetBytes(apiKey.ToString("N").ToLower())
);
string authentication = Convert.ToBase64String(
hmac.ComputeHash(
UTF8Encoding.UTF8.GetBytes(connectionId.ToString("N").ToLower())
)
);
As an example the following credentials:
Connection ID: 5fecbc200f0e4a7cbf41040e11047e56
API Key: 2de51c4fd0f04b9fabeb95225e87da70
Should result in a computed authentication value of
m5/Vc1RzhUETQvEtx/JdIglQpTg=
So what i have been trying is:
$a = strtolower('5fecbc200f0e4a7cbf41040e11047e56');
$b = strtolower('2de51c4fd0f04b9fabeb95225e87da70');
$z = hash_hmac("sha1", utf8_encode(decbin($b)), utf8_encode(decbin($a)), true);
dd(base64_encode($z));
Which outputs QjG3kzUs7U1UukNd++3t24pBWNk=
I have tried a few more variations, but I am just lost on this one. First time really decoding or encoding anything. Would greatly appreciate any tips, ideas, or snippets that can help me figure this out. Already spent a few hours on this and it's bugging me..
First: Get rid of utf8_encode() and just generally don't use it. It assumes that the input string is ISO-88591-1 and if it is anything else it will silently corrupt the data. This function has an incredibly misleading name, and I would go as far as to suggest that no one should ever use it or the corresponding utf8_decode() which will break your data in the same manner, but reversed.
If you need to convert string encodings in PHP use something that explicitly defines the input and output encodings, eg: mb_convert_encoding(). [you still don't need it for this]
Second: Whatever you think decbin() does, you're incorrect. It converts an integer into a literal, capital-S String composed of 0 and 1 characters.
Third: PHP strings have no inherent encoding and are roughly equivalent to byte arrays if you twisted my arm for a description. The bytes you put into them are the bytes you get out of them.
Fourth: I'm not exactly a C# expert [or intermediate, or even beginner] but that example code is horrendous. What even is the significance of the N in connectionId.ToString("N")? I can't find any documentation about this.
Start simple, use meaningful variable names, build up, and read the docs.
$connectionID = strtolower('5fecbc200f0e4a7cbf41040e11047e56');
$apiKey = strtolower('2de51c4fd0f04b9fabeb95225e87da70');
$hash = hash_hmac("sha1", $connectionID, $apiKey, true);
var_dump(base64_encode($hash));
Output:
string(28) "m5/Vc1RzhUETQvEtx/JdIglQpTg="
I'm using esp32 (Arduino platform not esp-idf) with the "HTTPClient.h" library to send get requests with parameters to my PHP server.
I want to encrypt the parameter values and decrypt them in my PHP code And vice versa (my server sends back JSON data to my esp32).
I tried using the XXTEA protocol with these libraries for PHP, and for esp32.
But the encrypted string won't decrypt properly on PHP.
Example:
When I encrypt "HELLO WORLD" on my esp32 with the key "ENCRYPTION KEY" I get this:
35bd3126715874f741518f4d
And when I decrypt it on PHP it returns blank.
Moreover, when I encrypt it on my PHP server I get this:
T1YNYC4P4R2Y5eCxUqtjuw==
My esp32 sketch looks like this:
#include <xxtea-iot-crypt.h>
void setup() {
Serial.begin(115200);
}
void loop() {
String plaintext = "HELLO WORLD";
// Set the Password
xxtea.setKey("ENCRYPTION KEY");
// Perform Encryption on the Data
Serial.print(F(" Encrypted Data: "));
String result = xxtea.encrypt(plaintext);
Serial.println(result);
// Perform Decryption
Serial.print(F(" Decrypted Data: "));
Serial.println(xxtea.decrypt(result));
delay(2000);
}
My PHP code looks like this:
require_once('xxtea.php');
$str = "HELLO WORLD"
$key = "ENCRYPTION KEY";
$encrypt_data = xxtea_encrypt($str, $key);
error_log($encrypt_data);
Is there a way to have an encrypted strings communication between PHP and esp32?
Thanks in advance.
This problem may result from inputs being of different data type, since no current XXTEA implementation seems to do any type or range checking.
Or it could be due to different endian behavior of the two computers involved, since binary is typically stored as an array of words constructed from bytes.
Or it could be due to lack of official or standard reference examples for correct encryption of a specific string and key. In the absence of reference examples (using either hexadecimal or base64 conversion of the binary encryption result) there is no way to tell whether an implementation of encryption is correct, even if its results decrypt correctly using a corresponding decryption implementation.
ADDED:
I think I've found one compatibility problem in the published code for XXTEA. It may be worth taking some space here to discuss it.
Specifically, the problem is that different implementations create different results for encrypting the same plaintext and key.
Discussion:
This problem results from the addition of the length of the plaintext as the last element of the array of longs. While this solves the problem of plaintext that has a length that is not a multiple of 4, it generates a different encrypted value than is generated by the JavaScript implementation.
If you insert "$w=false;" at the start of the long2str and str2long functions, the encrypted value for the PHP implementation becomes the same as the JavaScript implementation, but the decrypted value has garbage at the end.
Here are some test case results with this change:
PHP:
text: >This is an example. !##$%^&*(){}[]:;<
Base64: PlRoaXMgaXMgYW4gZXhhbXBsZS4gIUAjJCVeJiooKXt9W106Ozw=
key: 8GmZWww5T97jb39W
encrypt: sIubYrII6jVXvMikX1oQivyOXC07bV1CoC81ZswcCV4tkg5CnrTtqQ==
decrypt: >This is an example. !##$%^&*(){}[]:;<��
Note: there are two UTF-8 question-mark characters at the end of the "decrypt" line.
JavaScript:
text: >This is an example. !##$%^&*(){}[]:;<
Base64: PlRoaXMgaXMgYW4gZXhhbXBsZS4gIUAjJCVeJiooKXt9W106Ozw=
key: 8GmZWww5T97jb39W
encrypt: sIubYrII6jVXvMikX1oQivyOXC07bV1CoC81ZswcCV4tkg5CnrTtqQ==
decrypt: >This is an example. !##$%^&*(){}[]:;<
The reason there is no garbage in the JavaScript implementation even though it does not save the length of the plaintext is given in a comment there: "note running off the end of the string generates nulls since bitwise operators treat NaN as 0". In other words, the generated string is padded with NULs that are never seen, even though JavaScript, like PHP, can include NULs in strings because it stores the length separately.
I don't have an opinion about which approach is best, but one should be chosen for all implementations.
The reason that there should be a standard for the result of encryption (regardless of whether the binary is converted to hex or to base64 for safe transit) is that one might want to use, say, PHP for encoding but JavaScript for decoding, depending on which languages are natural to use at two locations. After all, encryption is most often used to communicate between two locations, and the language used at the target location might not even be known.
Why not using the wificlientsecure library? Works great on the esp32.
I'm trying to pass a message from a Javascript Client to a PHP webserver. To add a layer of security I would like to sign the data object with an hash.
/* Generate signature of the data with the password */
that.signEnvelope = function(data,password)
{
return CryptoJS.SHA256(JSON.stringify(data) + password).toString();
};
This quickly falls apart on the server. The JSON.stringify function does not generate a 1:1 matching string to json_encode on the server making it impossible to verify the hash.
protected function verifySignature($remoteSignature,$data,$privateKey)
{
/* Combine json & key samen , then sha256 */
$localSignature = hash('sha256',json_encode($data) . $privateKey);
return ($localSignature === $remoteSignature);
}
Is there another algorithm that I can implement in both PHP and Javascript that will generate a hashable string ?
Conclusion
Allowing json_encode accross platforms was not a smart thing todo. There is no standard implementation.
Instead I now only allow arrays with string key/value pairs which are much easier to concat and verify.
What you experiencing there is not limited to certain differing whitepace/linebreak-characters. It is also worth mentioning, that different charsets can lead to different output. A ISO8859-15 Euro-Sign is 1 byte long, a UTF8 Euro-Sign is 3 bytes long and there is always the chance to encode a Char with the \u####-declaration. JSON-libs is not intended to produce comparable strings over different plattforms.
If you still want to utilize JSON, you have to either use libs, that behave identical on all input, or build your own. JSON is easy to generate by hand.
You could use the JS version of json_encode to get a 1:1 match:
http://phpjs.org/functions/json_encode
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.