Home > Backend Development > PHP Tutorial > PHP calculates the SHA-1 hash function sha1() of a string

PHP calculates the SHA-1 hash function sha1() of a string

黄舟
Release: 2023-03-16 22:46:01
Original
1504 people have browsed it

Example

Calculate the SHA-1 hash of the string "Hello":

<?php
$str = "Hello";
echo sha1($str);
?>
Copy after login

Definition and usage

sha1() function calculates the SHA-1 of the string hash.

The sha1() function uses the American Secure Hash algorithm 1.

Explanation from RFC 3174 - US Secure Hash Algorithm 1: SHA-1 produces a 160-bit output called the message digest. The message digest can be fed into a signature algorithm that generates or verifies the message signature. Signing the message digest instead of the message can improve process efficiency because the size of the message digest is usually much smaller than the message. The verifier of a digital signature must use the same hashing algorithm as the creator of the digital signature.

Tip: To calculate the SHA-1 hash of a file, use the sha1_file() function.

Syntax

sha1(string,raw)
Copy after login

Parameters Description

string Required. Specifies the string to be calculated. ​

raw ​ Optional. Specifies hexadecimal or binary output format:

            TRUE - raw 20 character binary format

                FALSE - default. 40 character hexadecimal number

Technical details

Return value:                 Returns the calculated SHA-1 hash if successful, or FALSE if failed. ​

PHP Version: ​ 4.3.0+ ​

Update Log: ​ In PHP 5.0, the raw parameter becomes optional.

More examples

Instance 1

Output the result of sha1():

<?php 
$str = "Hello"; 
echo "The string: ".$str."<br>"; 
echo "TRUE - Raw 20 character binary format: ".sha1($str, TRUE)."<br>"; 
echo "FALSE - 40 character hex number: ".sha1($str)."<br>"; 
?>
Copy after login

Instance 2

Output the result of sha1() Result and test it:

<?php
$str = "Hello";
echo sha1($str);

if (sha1($str) == "f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0")
{
echo "<br>Hello world!";
exit;
}
?>
Copy after login


The above is the detailed content of PHP calculates the SHA-1 hash function sha1() of a string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template