★ wanayoo — archive 1999 http://www.php.net/manual/de/function.crypt.phpNouvelle recherche | Portail wanayoo

PHP Home Page

Manual Table of Contents
Up to Strings
Quick Reference
English version of this pageJapanese version of this pageItalian version of this pageFrench version of this pageHungarian version of this page
Strings
* AddCSlashes
* AddSlashes
* bin2hex
* Chop
* Chr
* chunk_split
* convert_cyr_string
* count_chars
* crypt
* echo
* explode
* flush
* get_html_translation_table
* get_meta_tags
* htmlentities
* htmlspecialchars
* implode
* join
* levenshtein
* ltrim
* md5
* Metaphone
* nl2br
* ob_start
* ob_get_contents
* ob_end_flush
* ob_end_clean
* ob_implicit_flush
* Ord
* parse_str
* print
* printf
* quoted_printable_decode
* QuoteMeta
* rawurldecode
* rawurlencode
* setlocale
* similar_text
* soundex
* sprintf
* strcasecmp
* strchr
* strcmp
* strcspn
* strip_tags
* StripCSlashes
* StripSlashes
* stristr
* strlen
* str_pad
* strpos
* strrchr
* str_repeat
* strrev
* strrpos
* strspn
* strstr
* strtok
* strtolower
* strtoupper
* str_replace
* strtr
* substr
* substr_count
* substr_replace
* trim
* ucfirst
* ucwords
Manual: crypt
View the source code for this pageSearch the site



Previous page
 count_chars
 Updated
Sat, 12 Aug 2000
echo 
Next page


crypt

(PHP3 , PHP4 )

crypt -- DES-Verschlüsselung eines Strings

Beschreibung:

string crypt (string str [, string salt])

Crypt() verschlüsselt einen String unter Verwendung der Standard-DES-Verschlüsselungs-Methode von Unix. Die zu übergebenden Argumente sind der zu verschlüsselnde String und optional ein 2-Zeichen-Salt-String, der die Schlüsselbasis bildet. Lesen sie die Man-Pages ihres Unix-Systems für mehr Informationen zu den Crypt-Funktionen.

Ist kein Salt-Argument angegeben, wird es von PHP nach dem Zufalls-Prinzip erzeugt.

Einige Betriebssystem unterstützen mehr als eine Methode zur Verschlüsselung. So wird manchmal der DES- durch einen MD5-Algorithmus ersetzt. Der verwendete Schlüssel wird durch das Salt-Argument bestimmt. Zur Installations-Zeit untersucht PHP die vorhandenen Möglichkeiten und wird, abhängig vom Ergebnis dieser Prüfung, auch andere Schlüssel-Typen zulassen. Wird kein Salt unterstützt, erzeugt PHP per Voreinstellung einen 2-Zeichen DES-Salt, es sei denn auf ihrem System existiert MD5. Dann wird PHP einen zufälligen MD5-Salt generieren. PHP erzeugt eine Konstante namens CRYPT_SALT_LENGTH. Diese besagt, ob ihr System ein reguläres 2-Zeichen Salt oder das längere 12-Zeichen MD5-Salt unterstützt.

Die Standard-DES-Verschlüsselung crypt() enthält das Salt als erste 2 Zeichen der Ausgabe.

Auf Systemen, wo die crypt()-Funktion meherere Verschlüsselungen unterstützt, werden die folgenden Konstanten auf 0 oder 1 gesetzt, je nachdem, ob der entsprechende Typ verfügbar ist:

  • CRYPT_STD_DES - Standard DES-Schlüssel mit 2-Zeichen Salt

  • CRYPT_EXT_DES - Erweiterter DES-Schlüssel mit einem 9-Zeichen Salt

  • CRYPT_MD5 - MD5-Schlüssel mit 12-Zeichen Salt, beginnend mit $1$

  • CRYPT_BLOWFISH - Erweiterter DES-Schlüssel, 16-Zeichen Salt, beginnend mit $2$

Der veschlüsselte String kann nicht entschlüsselt werden, da crypt() eine Einweg-Verschlüsselung ist.


User Contributed Notes: crypt


webmaster@l-i-e.com
30-Mar-1999 10:40
crypt() on operating systems where multiple encryption mechanisms are supported gets triggered by the actual salt you feed it. If you feed crypt a 2-char salt, then it will use DES encryption. If you feed it a 12-char salt starting with $1$ it will use MD5. If you feed it a 17-char salt starting with $2$ it will do Blowfish.


It has been theorized that feeding salt for an encryption method that is not supported by the OS will result in some other encryption being employed. If true, it might be possible to detect unsupported encryption methods by providing a salt and comparing the first n characters of the result with the provided salt.



improv@magma.ca
01-Aug-1999 01:35
for people using OS's without the crypt command available (i.e. at home on a Win32 system set up for testing purposes) the crypt command can be replaced with the following:


// this replaces $cryptString =
crypt($plainString, $salt);

$command = "perl -e \"print crypt('$plainString', '$salt');\"";

$cryptString = exec($command);


assuming you have perl installed, of course ;) also note that this only works with the standard two-character salt DES encryption.



lasse@email.dk
07-Aug-1999 07:25
If you want to make you own salt in php and don't trust the randomly generated one PHP provides I wrote a function that makes sure the salt is random enough....


function gensalt(){

function rannum(){

mt_srand((double)microtime()*1000000);

$num = mt_rand(46,122);

return $num;

}

function genchr(){

do{

$num = rannum();

} while ( ( $num > 57 && $num < 65 ) || ( $num > 90 && $num < 97 ) );

$char = chr($num);

return $char;

}

$a = genchr();

$b = genchr();

$salt = "$a$b";

return $salt;

}
$result = gensalt();

echo $result";


Best Regards
Lasse L. Johnsen



weirdal@vikingparty.dk
25-Jan-2000 03:57
If you want to crypt something that shall later be decrypted, you should instead use the encrypt() and decrypt() functions.


weirdal@vikingparty.dk
30-Jan-2000 03:21
As I see it, the crypt() function doesn't support decryption (This is simply a security matter, so that you have to have the exact same string that once was crypted, then crypt it using crypt(), and compare the old crypted string with the new one.)

It's also right that you then don't have the ability to (for example) send a user his or hers password to their e-mail address - because you don't know it your self... you only have the crypted version of the password.

I looked at the online PHP manual and didn’t find the two functions encrypt() and decrypt(). Therefore I've taken the liberty to quote the great book "Core PHP Programming" by Leon Atkinson, where to two functions are discussed:


First the decrypt() function:

string decrypt(string data, integer method, string key)

The decrypt() function attempts to transform an encrypted string passed as the data argument into plain text using the method specified by the method argument and the key from the key argument. Each of the four methods uses a single key that both encrypts and decrypts. The methods are listed below:


METHOD: NAME: MINIMUM DATA LENGTH: REQUIRED KEY SIZE:

0 IDEA 8 characters 16 characters

1 MDC 8 characters 8 characters

2 DES 32 characters 16 characters

3 XOR 16 characters 16 characters



Then the encrypt() function:

string encrypt(string data, integer method, string key)

To encrypt the data you wish to later decrypt, use the encrypt() function. Data are encrypted using one of four methods and a key. See the description of the decrypt() function for more information.


Example:


$message = "this is a plain text message";

$password = "secret";

$data = encrypt($message, 0, $password);

print(decrypt($data, 0, $password));


Once again (I've been getting some e-mails on this subject): the crypt() function is a one-way-algorithm - There is no way to decrypt the information crypted with crypt(). If you want to crypt something that shall later be decrypted, you can use the encrypt() and decrypt() function (as I've discussed above, but the two functions are not enabled by default in PHP3 - See further down on how to do this).


While working with PHP and crypting I've also discovered another function: "md5()". This function does the same as crypt(), but while crypt() doesn't work on a windows platform (as far as I know) the md5() does. The md5() is by far more secure than crypt() as crypt() only looks at the 1st 8 chars.


To find out how the two functions encrypt() and decrypt() works, I contacted Leon Atkinson, author of "Core
PHP Programming". Here is what he wrote:


--------------------------------


There's two problems. First, you need to enable the php3_crypt.dll to make the functions available. You can do that either by uncommenting the line:

extension=php3_crypt.dll


in your php3.ini file, or you can use dl(), such as:


dl("extension=php3_crypt.dll");


prior to calling the functions. The
second problem is that these functions have seem to be abandoned in PHP4 in favor of a new module called mcrypt. But the mcrypt functions aren't available for PHP3. If you want to play around with these functions, you may need to change my example. It didn't run for me in 3.0.12 until I changed the password to be 16 characters long.

Good Luck,

Leon



--------------------------------


- Watson



karel@publihost.com
05-Feb-2000 08:56
With this code you can make your one encrypting. Put it in a file xor.php3:
The code is: dfgsdfg452
The first xor: abcde
The second xor: edcba


$i = "dfgsdfg452";
$s = "abcde";
$p = "edcba";


for($x=0; $x < strlen($i); $x++)
{
$i[$x] = chr(ord($i[$x]) ^ ord($s[$x % strlen($s)]) ^ ord($p[$x % strlen($p)]));
}

echo "<form method='POST' action='/old?u=http%3A%2F%2Fwww.php.net%2Fmanual%2Fde%2Fxor.php3&y=1999'>";
echo "<input type='text' name='encrip' value='$i'>";
echo "<input type='submit' name='Submit' value='a'>";
echo "</form>";

if ( $Submit == "a")
{
$k = $encrip;
$l = "abcde";
$p = "edcba";


for($x=0; $x < strlen($k); $x++)
{
$k[$x] = chr(ord($k[$x]) ^ ord($l[$x % strlen($l)]) ^ ord($p[$x % strlen($p)]));
}

echo"$k";
echo"dfgsdfg452";
}

the result is:


<form method='POST' action='/old?u=http%3A%2F%2Fwww.php.net%2Fmanual%2Fde%2Fxor.php3&y=1999'><input type='text' name='encrip' value='``gu`ba436'><input type='submit' name='Submit' value='a'></form>

dfgsdfg452 dfgsdfg452



martinmv@penguin.cz
12-Apr-2000 08:49
There is PHP for win32 with function crypt (binary and changed source).




<A HREF=/old?u=http%3A%2F%2Fwww.php.net%2Fmanual%2Fde%2F%26quot%3Bhttp%3A%2Fwww.penguin.cz%2F~martinmv%2Fphp-3.0.15.win32.tar.bz2%26quot%3B%26gt%3Bphp-3.0.15.win32.tar.bz2%26lt%3B%2FA%26gt&y=1999




hall@cs.unt.edu
13-Apr-2000 09:26
I've been reading these comments and noticed some bad things about the PHP encryption functions and some people's understanding of them.


First, the encrypt() and decrypt() functions talked about earlier use symmetric encryption; that is, the same key that encrypts also decrypts. So, if your key (the third argument to both functions) isn't kept completely private, you may as well have sent plaintext.


Second, MD5 is not really encryption. It is a cryptographic hash function. It is not used to encrypt data really. It is used to test whether a message has been altered during transit. It is "cryptographically secure" because if I send you an encrypted message with the plaintext's MD5 hash value, and a middle-man alters the encrypted message (but can't recalculate the MD5 hash value of the message, b/c it's encrypted), the MD5 hash of the plaintext that you compute will differ from mine. Then you'll know that somebody altered it. It's not used for encryption because it's a many-to-one hash function. Many, many plaintexts will map to one MD5 value. Valid encryption does not work this way. MD5 is also a one-way function, meaning that you cannot (without much difficulty) reproduce the same plaintext with its MD5 hash value.


You can use crypt (for passwords), md5() for a cryptographic hash function, and encrypt()/decrypt() in conjunction for some really good security on your website (but don't forget that unless you use SSL or some other encryption on the client-side that everything's being sent in plaintext).


What I would suggest to the creators of PHP is to write functions that use public cryptography -- algorithms like RSA -- so that we have more options. Implementing some sort of Kerberos-type authentication might work with cookies, also.


_Cryptography and Network Security_ by William Stallings is a good book on this stuff.


dn



hall@cs.unt.edu
14-Apr-2000 12:21

Ah, I remembered something VERY important!!!



NEVER, EVER, EVER use a simple XOR to encrypt data (except, MAYBE with a one-time pad in certain circumstances). If I have plaintext <code>x</code> and I <code>XOR</code> it with <code>y</code>, like so: <code>x XOR y = z</code>, then you know what? If some malicious guy, Mark, knows the plaintext, he can just do this: <code>z XOR x = y</code>. Now Mark knows your key. If he knows the key, he can get your plaintext: <code>y + z = x</code>.

Now, with symmetric ciphers like DES and Blowfish, if somebody knows your key, they can decrypt your data or encrypt it and pose as you. But it would be really difficult for someone to get your key if they knew the plaintext and the ciphertext. With XOR, somebody can get your key with the plaintext. NOT GOOD . . . perhaps unless it's a one-time pad (i.e., the key is as long as the plaintext (you don't have to repeat it), it's REALLY random, and you never use it again).

I'm not sure if the PHP encrypt uses a plain XOR cipher (in XOR mode), but it would be horrible if it did.

Just so you know.

Dean.



rtdean@cytherianage.net
19-May-2000 03:05
I took the nice salt generator listed above and improved on it a little bit. It works well, I needed to set up user authentication for a site I was working on, and I quested a bit the information provided below, so enjoy!

function rannum(){
mt_srand((double)microtime()*1000000);
$num = mt_rand(46,122);
return $num;
}

function genchr(){
do{
$num = rannum();
} while ( ( $num > 57 && $num < 65 ) || ( $num > 90 && $num < 97 ) );
$char = chr($num);
return $char;
}

function saltstr($size){
for($i=1;$i<=$size;$i++) {
$string = $string.genchr();
}
return $string;
}

function gensalt($type){
if($type == "des-std") { /* des-standard salt (2 chr) */
return saltstr(2);
} else if ($type == "des-ext") { /* des-extended salt (9 chr) */
return saltstr(9);
} else if ($type == "md5") { /* md5 salt (12 char, starts with $1$ ends with $ */
$tmpslt = saltstr(8);
return sprintf("$1$%s$",$tmpslt);
} else if ($type == "blowfish") { /* blowfish salt (16 char, starts with $2$ ends with $ */
$tmpslt = saltstr(13);
return sprintf("$2$%s$",$tmpslt);
} else { /* Catch everything else to des-std */
return saltstr(2);
}
}

Then you just call $salt = gensalt("md5"); or ("des-std"); and it returns the salt requested. Actually, you could feed it straight into crypt as the second argument.

If you are using des-std, md5, or blowfish, and are validating a password presented by a user against a password stored, say from a database, just feed the database password as the salt to the presented password. IE $stored being the password stored on the server, and $presented being the password presented, you could do something like:

if ($stored == crypt($presented, $stored)) {
// Password valid
} else {
// Password invalid
}

Based on the first couple of characters ($1$, $2$, or nothing) it desides which crypt() method to use, and crypts the password appropriately. So if it starts with $1$, it will md5 crypt the message using the first 12 chars of the stored password (the salt). If $2$ it will use 16, and nothing it will use two. I have no idea if it will work with des-ext, as I have no method of testing, however I would assume so (based on overall crypted string length) but thats just a guess.

In any case, I quested for a bit for this and I hope this will help someone else questing for information.



anon@anon.com
09-Jul-2000 08:10
i really needed an encrypt/decrypt under windoze98 php4, and i ran across the encode/decode for mySQL. So i decided to use that... i hope that helps some of u guys.

// encode(string encode_str, password_str);
// decode(string decode_str, password_str);
// my own personal encode/decode functions using MySQL
// a MySQL connection MUST be already open to use it!

/////// encryption functions (MySQL)
function encode($encode_str, $pass_str) {
$data = mysql_query("select encode('$encode_str', '$pass_str')");
$row = mysql_fetch_row($data);
return $row[0];
}
function decode($decode_str, $pass_str) {
$data = mysql_query("select decode('$decode_str', '$pass_str')");
$row = mysql_fetch_row($data);
return $row[0];
}
function password($string) {
$data = mysql_query("select password('$string')");
$row = mysql_fetch_row($data);
return $row[0];
}


Chao Xiong



peter@noemail.please.com
12-Jul-2000 10:17
In response to dn (hall@cs.unt.edu)


There is no reason MD5 cannot be used as a hash function for password protection.


MD5, like all hash functions, is designed to minimise the possibility of collisions. A hash function would not be very secure if it did not do this.


Quoting from the MD5 RFC (refer to http://www.normos.org/ietf/rfc/rfc1321.txt)
"It is conjectured that the difficulty of coming up with two messages having the same message digest is on the order of 2^64 operations, and that the difficulty of coming up with any message having a given message digest is on the order of 2^128 operations."


Those people recommending XOR to encrypt sensitive information should look at any security book before doing such a silly thing.


And I agree that William Stalling's book is excellent :-)



arw@island.net
12-Jul-2000 06:38
I see some of you are looking for encrypted passes but also want the copy in the db to be able to be accessed.... now im no security expert or anything, so i dont know if this is secure enough for ya, but what ive found is that if you pull a copy of the users password from a db and crypt it then match that to the crypted pass from the form you should be able to match them or not....


ie:


/* you found this at php.net under crypt forum */

/* your db search goes here.... select * from where id = '$user' */



$mysql_pass = urlencode(crypt(mysql_result($result,0,"pass"),32));



if ($mysql_pass == $encrypted_pass){
$logged = 1;

}


this way you can show the encrypted pass in the history and not be able to decipher what it is....

adam



mikebabcock@pobox.com
30-Jul-2000 10:34

It seems that a lot of people don't understand the point of using one-way encryption. More importantly, a lot of web designers forget that PHP encryption is done entirely on the web server, not the client.



Point being, if your form has a password input option and the user clicks SUBMIT, the password is then sent _as plain text_ over the Internet to the web server where it is then encrypted for comparison against a password database.



Do _not_ use these types of functions to add security to a form unless you're using an SSL or TLS (etc.) encrypted session. The only potential way around this issue is for you to write a JavaScript program that does the hashing on the client side before being sent over the Internet (which would make this function unnecessary).



Remember: SSL!




 About Notes


Previous page
 count_chars
 Updated
Sat, 12 Aug 2000
echo 
Next page





Who's responsible for this?
Top of this page

Site
Hosting:



Located in
United States
Elements of this website are subject to copyright.
Questions about installing or using PHP should be directed to one of the mailing lists.
Only questions about the website should be directed to webmaster@php.net.