SHA2 Function
Overview
The SHA2 function is a unified interface for the SHA-2 family of hash algorithms, allowing selection of a specific SHA-2 variant (SHA-224, SHA-256, SHA-384, SHA-512) via the bit_length parameter. The SHA-2 family of algorithms can map arbitrary-length data to fixed-length hash values, outputting a hexadecimal string whose length depends on the chosen variant.
Syntax
sha2(expr, bit_length)
Parameters
expr: The input data for which to compute the hash value. Supports STRING, VARCHAR, CHAR, and BINARY types.bit_length: Integer type (INT), specifying which SHA-2 variant to use. Supports the following values:0— equivalent to 256, uses the SHA-256 algorithm224— uses the SHA-224 algorithm, outputs a 56-character hexadecimal string256— uses the SHA-256 algorithm, outputs a 64-character hexadecimal string384— uses the SHA-384 algorithm, outputs a 96-character hexadecimal string512— uses the SHA-512 algorithm, outputs a 128-character hexadecimal string
Return Result
Returns a STRING type value representing the computed hexadecimal hash string. The output length depends on the bit_length parameter:
| bit_length | Output Length (characters) |
|---|---|
| 0 or 256 | 64 |
| 224 | 56 |
| 384 | 96 |
| 512 | 128 |
Examples
-
Compute the hash value using SHA-256 (bit_length=256):
-
Compute the hash value using SHA-224 (bit_length=224):
-
Compute the hash value using SHA-384 (bit_length=384):
-
Compute the hash value using SHA-512 (bit_length=512):
-
Using bit_length=0 (equivalent to SHA-256):
-
When the input is NULL:
Notes
- When the input parameter
expris NULL, the result is NULL. - When
bit_lengthis 0, it is equivalent tobit_lengthbeing 256, using the SHA-256 algorithm. - When
bit_lengthis not one of 0, 224, 256, 384, or 512, the function will throw an error. - SHA-2 series hash values are irreversible, meaning the original data cannot be derived from the hash value.
- If you only need to use a fixed SHA-2 variant, you can also use the corresponding standalone functions directly:
sha224(),sha256(),sha384(),sha512().
