PHP Encryption Functions

by kalai 2009-11-07 15:55:10

Default PHP Encryption Functions
PHP ships with three built-in encryption functions: md5(), crypt(), and sha1(). The md5() function prototype is:

string md5(string $str [, bool $raw_output ])

The function calculates the MD5 hash of a supplied string using the MD5 Message-Digest algorithm. The $str argument represents the string to be encrypted. If you pass FALSE in the $raw_output argument (the default), the function returns the hash as a 32-character hexadecimal number. If you pass TRUE then the function returns a 16-byte raw binary value.

The PHP crypt() function is a one-way encryption function that lets you confirm that an entered password matches a stored encrypted oneЧwithout having to decrypt anything. The crypt() function prototype is:

string crypt (string $str [, string $salt ])

It returns an encrypted string using the standard Unix DES-based encryption algorithm (or alternative algorithms that may be available on the system). The $str argument is the string to be encrypted and the optional $salt argument is a string on which to base the encryption. If you don't provide the salt string, PHP will randomly generate one each time you call this function.

The PHP sha1() function calculates the SHA-1 hash of a string. The sha1() function prototype is:

string sha1 (string $str [, bool $raw_output ])


Figure 1. Encrypted File: The encrypted.txt file contains a password encrypted with md5, crypt, and sha1 PHP default functions.
The function returns the SHA-1 hash as a string. Again, the $str argument represents the input string. If you set the optional $raw_output argument to TRUE, the function returns the sha1 hash in raw binary format with a length of 20 characters; if you set it to FALSE, it returns a 40-character hexadecimal number.

As an example, the following code shows how to use the PHP default encryption functions to encrypt the contents of texfile.txt file and write the encrypted result in the file encrypted.txt (see Figure 1):


$file = 'textfile.txt';
$initial_contents = file_get_contents($file);

if($initial_contents){

$password = 'OctaviaAnghel';

//Calculates the md5 hash
$md5_data = md5($password);

//This function encrypts data
$crypt = crypt($password);

//Calculate the sha1 hash
$sha1 = sha1($password);

$encrypted_file = @fopen('encrypted.txt','w');
$ok_encrypt = @fwrite($encrypted_file,'md5: '. $md5_data."rn".'crypt:
'.$crypt."rn".'sha1: '.$sha1);

if($ok_encrypt){
echo 'The encrypted code was succesfully created'.
' in encrypted_file.txt!!!'.'
';
}
else{
echo ("The write of this file failed!");
}

@fclose($encrypted_file);
}
?>


In addition to the built-in functions, PHP supports encryption via external libraries and packages.

Tagged in:

2316
like
0
dislike
0
mail
flag

You must LOGIN to add comments