<?php

/*
 * TIT Systems CDN - PWNED API check
 * Example code for checking a password against the PWNED API
 *
 * @author Florian Thie
 * @copyright Copyright (c) Florian Thie 2018
 */

/*
 * This functions checks whether the password provided has already been compromised.
 * It returns TRUE, if $password is NOT known to be compromised.
 * It returns FALSE, if the passwords hash was found, so that the password has very likely been compromised.
 * If an error occurs during the execution of the function (API not reachable etc.) you can specifiy a default return with the parameter $onerror_return.
 */
function pwcheck_titcdn_pwnedapi($password, $onerror_return = FALSE) {
	
	/* Generate a SHA-1 hash */
	$hash = hash('sha1', $password);
	
	/* Get the first 6 hex characters / first 24 bits of the hash */
	$prefix = substr($hash, 0, 6);
	
	/* Call the API with the prefix */
	$answer = file_get_contents('https://pwned.tit-cdn.de/'.$prefix);
	
	/* If there was an error, return the onerror_return value */
	if($answer === FALSE) {
		return $onerror_return;
	}
	
	/* Split the answer into an array of its lines */
	$result_hashes = explode('
', $answer);
	
	/* Get the returned prefix */
	$prefix_return = trim($result_hashes[0]);
	
	/* Check the returned prefix to see, if the API call was successful */
	if(strlen($prefix_return) != 6 || $prefix != $prefix_return) {
		return $onerror_return;
	}
	
	/* Loop through the returned hashes */
	foreach($result_hashes as $result_hash) {
		/* Trim the hash */
		$result_hash = trim($result_hash);
		
		/* Check whether its length is valid */
		if(strlen($result_hash) != 40) {
			continue;
		}
		
		/* Check whether the current hash matches our own */
		if($hash == $result_hash) {
			return FALSE;
		}
	}
	
	/* GREAT, we did not find our password hash! */
	return TRUE;
}

?>