PHP Function Reference

PHP sha1() Function



The PHP sha1() function calculates the SHA-1 (Secure Hash Algorithm 1) hash of string using the US Secure Hash Algorithm 1.

From RFC 3174: SHA-1 produces a condensed representation of a message or a data file. When a message of length less than 264 bits is input, the SHA-1 produces a 160-bit output called a message digest. The message digest can then, for example, be input to a signature algorithm which generates or verifies the signature for the message. Signing the message digest rather than the message often improves the efficiency of the process because the message digest is usually much smaller in size than the message. The same hash algorithm must be used by the verifier of a digital signature as was used by the creator of the digital signature. Any change to the message in transit will, with very high probability, result in a different message digest, and the signature will fail to verify.

Note: It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm.

Syntax

sha1(string, binary)

Parameters

string Required. Specify the input string.
binary Optional. If set to true, then the SHA-1 digest is returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number. Default is false.

Return Value

Returns the SHA-1 hash as a string.

Example:

The example below illustrates on sha1() function.

<?php
$str = "Hello";

echo "The string is: $str \n";
echo "The hash of string is: \n";
echo sha1($str);
?>

The output of the above code will be:

The string is: Hello 
The hash of string is: 
f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0

Example:

Consider one more example where optional parameter is used to calculate the hash of the string in different formats.

<?php
$str = "Hello";

echo "20 character binary format:\n";
echo sha1($str, true);
echo "\n40 character hexadecimal number: \n";
echo sha1($str);
?>

The output of the above code will be:

20 character binary format:
÷ÿž‹{²à›p“Z]x^ÅÙЫð
40 character hexadecimal number: 
f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0

❮ PHP String Reference