Check if string is md5 php

Php – Check if string is an MD5 Hash

I accidentally stopped hashing passwords before they were stored, so now my database has a mix of MD5 Passwords and unhashed passwords.

I want to loop through and hash the ones that are not MD5. Is it possible to check if a string is an MD5 hash?

Best Solution

You can check using the following function:

function isValidMd5($md5 ='') < return preg_match('/^[a-f0-9]$/', $md5); > echo isValidMd5('5d41402abc4b2a76b9719d911017c592'); 

The MD5 (Message-digest algorithm) Hash is typically expressed in text format as a 32 digit hexadecimal number.

This function checks that:

Mysql – What data type to use for hashed password field and what length

Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.

For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt by default.

$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT); 

The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a 

Use the SQL data type CHAR(60) to store this encoding of a Bcrypt hash. Note this function doesn’t encode as a string of hexadecimal digits, so we can’t as easily unhex it to store in binary.

Other hash functions still have uses, but not for storing passwords, so I’ll keep the original answer below, written in 2008.

It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the UNHEX() function to reduce a string of hex digits by half.

  • MD5 generates a 128-bit hash value. You can use CHAR(32) or BINARY(16)
  • SHA-1 generates a 160-bit hash value. You can use CHAR(40) or BINARY(20)
  • SHA-224 generates a 224-bit hash value. You can use CHAR(56) or BINARY(28)
  • SHA-256 generates a 256-bit hash value. You can use CHAR(64) or BINARY(32)
  • SHA-384 generates a 384-bit hash value. You can use CHAR(96) or BINARY(48)
  • SHA-512 generates a 512-bit hash value. You can use CHAR(128) or BINARY(64)
  • BCrypt generates an implementation-dependent 448-bit hash value. You might need CHAR(56), CHAR(60), CHAR(76), BINARY(56) or BINARY(60)

As of 2015, NIST recommends using SHA-256 or higher for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.

Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are known to be crackable.

Is “double hashing” a password less secure than just hashing it once

Hashing a password once is insecure

No, multiple hashes are not less secure; they are an essential part of secure password use.

Iterating the hash increases the time it takes for an attacker to try each password in their list of candidates. You can easily increase the time it takes to attack a password from hours to years.

Simple iteration is not enough

Merely chaining hash output to input isn’t sufficient for security. The iteration should take place in the context of an algorithm that preserves the entropy of the password. Luckily, there are several published algorithms that have had enough scrutiny to give confidence in their design.

A good key derivation algorithm like PBKDF2 injects the password into each round of hashing, mitigating concerns about collisions in hash output. PBKDF2 can be used for password authentication as-is. Bcrypt follows the key derivation with an encryption step; that way, if a fast way to reverse the key derivation is discovered, an attacker still has to complete a known-plaintext attack.

How to break a password

Stored passwords need protection from an offline attack. If passwords aren’t salted, they can be broken with a pre-computed dictionary attack (for example, using a Rainbow Table). Otherwise, the attacker must spend time to compute a hash for each password and see if it matches the stored hash.

All passwords are not equally likely. Attackers might exhaustively search all short passwords, but they know that their chances for brute-force success drop sharply with each additional character. Instead, they use an ordered list of the most likely passwords. They start with «password123» and progress to less frequently used passwords.

Let’s say an attackers list is long, with 10 billion candidates; suppose also that a desktop system can compute 1 million hashes per second. The attacker can test her whole list is less than three hours if only one iteration is used. But if just 2000 iterations are used, that time extends to almost 8 months. To defeat a more sophisticated attacker—one capable of downloading a program that can tap the power of their GPU, for example—you need more iterations.

How much is enough?

The number of iterations to use is a trade-off between security and user experience. Specialized hardware that can be used by attackers is cheap, but it can still perform hundreds of millions of iterations per second. The performance of the attacker’s system determines how long it takes to break a password given a number of iterations. But your application is not likely to use this specialized hardware. How many iterations you can perform without aggravating users depends on your system.

You can probably let users wait an extra ¾ second or so during authentication. Profile your target platform, and use as many iterations as you can afford. Platforms I’ve tested (one user on a mobile device, or many users on a server platform) can comfortably support PBKDF2 with between 60,000 and 120,000 iterations, or bcrypt with cost factor of 12 or 13.

More background

Read PKCS #5 for authoritative information on the role of salt and iterations in hashing. Even though PBKDF2 was meant for generating encryption keys from passwords, it works well as a one-way-hash for password authentication. Each iteration of bcrypt is more expensive than a SHA-2 hash, so you can use fewer iterations, but the idea is the same. Bcrypt also goes a step beyond most PBKDF2-based solutions by using the derived key to encrypt a well-known plain text. The resulting cipher text is stored as the «hash,» along with some meta-data. However, nothing stops you from doing the same thing with PBKDF2.

Here are other answers I’ve written on this topic:

Related Question

Источник

Check if string is md5 php

md5 — Calculate the md5 hash of a string

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices.

Description

Calculates the MD5 hash of string using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

Parameters

If the optional binary is set to true , then the md5 digest is instead returned in raw binary format with a length of 16.

Return Values

Returns the hash as a 32-character hexadecimal number.

Examples

Example #1 A md5() example

if ( md5 ( $str ) === ‘1f3870be274f6c49b3e31a0c6728957f’ ) echo «Would you like a green or red apple?» ;
>
?>

See Also

  • md5_file() — Calculates the md5 hash of a given file
  • sha1_file() — Calculate the sha1 hash of a file
  • crc32() — Calculates the crc32 polynomial of a string
  • sha1() — Calculate the sha1 hash of a string
  • hash() — Generate a hash value (message digest)
  • crypt() — One-way string hashing
  • password_hash() — Creates a password hash

User Contributed Notes 7 notes

This comparison is true because both md5() hashes start ‘0e’ so PHP type juggling understands these strings to be scientific notation. By definition, zero raised to any power is zero.

Regarding Ray Paseur’s comment, the strings hash to:

The odds of getting a hash exactly matching the format /^0+e3+$/ are not high but are also not negligible.

It should be added as a general warning for all hash functions to always use the triple equals === for comparison.

Actually, the warning should be in the operators section when comparing string values! There are lots of warnings about string comparisons, but nothing specific about the format /^0+e1+$/.

If you want to hash a large amount of data you can use the hash_init/hash_update/hash_final functions.

This allows you to hash chunks/parts/incremental or whatever you like to call it.

I’ve found multiple sites suggesting the code:

Until recently, I hadn’t noticed any issues with this locally. but then I tried to hash a 700MB file, with a 2048MB memory limit and kept getting out of memory errors.

There appears to be a limit to how long a string the md5() function can handle, and the alternative function is likely more memory efficient anyway. I would highly recommend to all who need file hashing (for detecting duplicates, not security digests) use the md5_file() function and NOT the regular string md5() function!

Note, to those interested, as this was for a local application not a server, I was more concerned with results than memory efficiency. In a live environment, you would never want to read an entire file into memory at once when avoidable. (at the time of coding, I did not know of the alternative function)

From the documentation on Digest::MD5:
md5($data. )
This function will concatenate all arguments, calculate the MD5 digest of this «message», and return it in binary form.

md5_hex($data. )
Same as md5(), but will return the digest in hexadecimal form.

PHP’s function returns the digest in hexadecimal form, so my guess is that you’re using md5() instead of md5_hex(). I have verified that md5_hex() generates the same string as PHP’s md5() function.

(original comment snipped in various places)
>Hexidecimal hashes generated with Perl’s Digest::MD5 module WILL
>NOT equal hashes generated with php’s md5() function if the input
>text contains any non-alphanumeric characters.
>
>$phphash = md5(‘pa$$’);
>echo «php original hash from text: $phphash»;
>echo «md5 hash from perl: » . $myrow[‘password’];
>
>outputs:
>
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd

function raw2hex ( $rawBinaryChars )
return = array_pop ( unpack ( ‘H*’ , $rawBinaryChars ));
>
?>

The complement of hey2raw.
You can use to convert from raw md5-format to human-readable format.

This can be usefull to check «Content-Md5» HTTP-Header.

$rawMd5 = base64_decode ( $_SERVER [ ‘HTTP_CONTENT_MD5’ ]);
$post_data = file_get_contents ( «php://input» );

if( raw2hex ( $rawMd5 ) == md5 ( $post_data )) // Post-Data is okay
else // Post-Data is currupted
?>

Note: Before you get some idea like using md5 with password as way to prevent others tampering with message, read pages «Length extension attack» and «Hash-based message authentication code» on wikipedia. In short, naive constructions can be dangerously insecure. Use hash_hmac if available or reimplement HMAC properly without shortcuts.

Источник

Regex to match md5 hashes

What type of regex should be used to match a md5 hash. how to validate this type of string 00236a2ae558018ed13b5222ef1bd987 i tried something like this: (‘/^[a-z0-9]/’) but it didnt work. how to achieve this? thanks

If you’re given a string and you want to validate it as md5, simply check for length 32 and characters a-f0-9.

By «validate», do you simply mean that any 32-character string containing only valid hexadecimal digits will pass?

The simplicity of the question — The first search result on Google happens to be a duplicate on this very site. as a general rule of thumb: if you get an immediate answer, you probably didn’t put enough effort into the question.

2 Answers 2

This is a PCRE that will match a MD5 hash:

define('R_MD5_MATCH', '/^[a-f0-9]$/i'); if(preg_match(R_MD5_MATCH, $input_string)) < echo "It matches."; >else

Beware of hashes with upper-case literals. Both upper and lower case are valid so eliminating the one or the other is not correct. The regex should probably look like this: ‘/^[a-fA-F0-9]<32>$/i’ . Cheers.

@el.nicko I’m trying to understand . since the regex includes i for case-insensitive, why specify both a-f and A-F ? Do you have any links to back-up/expand-upon your point?

@el.nicko this wouldn’t matter because it’s got the i modifier. The reason only the lowercase range is there and not both is because of the i modifier.

ACK, you’ve got a point there. In the context of the question and the given answer you are 100% correct. There are some setups though (e.g. java) where the i won’t work or at least not as expected, but adding the upper and lower case works and enhances readability depending on how one sees it 🙂

These are PCRE’s . How Java does it is not relevant. Regular Expressions aren’t always portable across engines.

Источник

Читайте также:  Заголовок страницы
Оцените статью