summaryrefslogtreecommitdiffstats
path: root/inc/crypto.inc.php
blob: acefcf672bd0e625e4de7138b1aa45a2572530de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

declare(strict_types=1);

class Crypto
{

	/**
	 * Hash given string using crypt's $6$,
	 * which translates to ~130 bit salt
	 * and 5000 rounds of hashing with SHA-512.
	 */
	public static function hash6(string $password): string
	{
		$bytes = Util::randomBytes(16);
		if ($bytes === null)
			ErrorHandler::traceError('Could not get random bytes');
		$salt = substr(str_replace('+', '.',
			base64_encode($bytes)), 0, 16);
		$hash = crypt($password, '$6$' . $salt);
		if ($hash === null || strlen($hash) < 60) {
			ErrorHandler::traceError('Error hashing password using SHA-512');
		}
		return $hash;
	}

	/**
	 * Check if the given password matches the given crypt hash.
	 * Useful for checking a hashed password.
	 */
	public static function verify(string $password, string $hash): bool
	{
		return crypt($password, $hash) === $hash;
	}

}