Fingerprint an SSH key using PHP

A project I'm working on requires displaying the fingerprint of an SSH key. Without wanting to use exec to get the fingerprint, I wrote this:

/**
 * Returns the fingerprint of an SSH key.
 *
 * @param string $key The SSH key to fingerprint
 *
 * @return string
 */ 
function fingerprint($key) {  
    $cleanedKey = preg_replace('/^(ssh-[dr]s[as]\s+)|(\s+.+)|\n/', '', trim($key));
    $buffer = base64_decode($cleanedKey);
    $hash = md5($buffer);

    return preg_replace('/(.{2})(?=.)/', '$1:', $hash);
}

comments powered by Disqus