Published on

# Regex for SHA256 string

In this article let's understand how we can create a regex for SHA256 strings and how it can be matched.

SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that is used to generate a fixed-size, 64-character (256-bit) output from any input data. It is commonly used to verify the integrity of data, such as files downloaded from the internet, and to generate digital signatures for electronic documents.

Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.

Let's look at regex expression for base64 strings. We will try a few approaches right from simple approach to RFC or advanced approach.

# Regex to match SHA256 string

Regular Expression for SHA256 String can be represented as-

/^[a-fA-F0-9]{64}$/gm  Alternatively you can use the i modifier in the regex takes care of the UPPERCASE letters. /^[a-f0-9]{64}$/i


Test string examples for the above regex-

Input StringMatch Output
ThisIsNotSHA256does not match
a1f0b78b8c1320690327800e3a5de10e7dbba7b6c752e702193a395a52c727b6matches
b32433a2e42321239baca23bf9c77889fccc5483fc142a31cdf07d115e44fc79matches
zxcvbncvwfrqghdfjgyetwrteyrutituregfwfeghrgjhkjgfdsdghjdoes not match

Here is a detailed explanation of the above regex-

/^[a-fA-F0-9]{64}$/gm ^ asserts position at start of a line Match a single character present in the list below [a-fA-F0-9] {64} matches the previous token exactly 64 times a-f matches a single character in the range between a (index 97) and f (index 102) (case sensitive) A-F matches a single character in the range between A (index 65) and F (index 70) (case sensitive) 0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and \$ to match the begin/end of each line (not only begin/end of string)