~mikini/hometools

da42685449e49281b1a5c05c2946c38f325a9202 — Mikkel Kirkgaard Nielsen a month ago 30788f6
Cleanup to aid usage on cmd line and in scripts

* return exit code indicating whether valid arguments are supplied
* write help and error to stdout to be able to filter it in scripts
* remove superfluous newlines from output
1 files changed, 7 insertions(+), 6 deletions(-)

M mosquitto_passwd.php
M mosquitto_passwd.php => mosquitto_passwd.php +7 -6
@@ 1,6 1,6 @@
#! /usr/bin/php

<?php

// Create a line with obfuscated credentials meant to be used in a file given to
// Mosquitto MQTT broker's password_file option (mosquitto.conf(5),
// https://mosquitto.org/man/mosquitto-conf-5.html) and thus compatible with the


@@ 11,20 11,21 @@
// https://mikini.dk/2017/01/generating-passwords-for-mosquitto-mqtt-broker-using-php

if ($argc >= 3) {
    echo ("Add the obfuscated line below to Mosquitto's password file to authenticate with the provided credentials:\n\n");
    echo (mosquitto_password($argv[1], $argv[2])."\n");
    fwrite(STDERR, "Add the obfuscated line below to Mosquitto's password file to authenticate with the provided credentials:\n\n");
    fwrite(STDOUT, mosquitto_password($argv[1], $argv[2])."\n");
    exit(0);
}
else {
    echo("ERROR: Supply username and password as arguments in that order.\n");
    fwrite(STDERR, "ERROR: Supply username and password as arguments: " . $argv[0] . " <username> <password>\n");
    exit(1);
}

function mosquitto_password($username, $password) {
    $salt_base64 = base64_encode(openssl_random_pseudo_bytes(12));
//    $salt_base64="mfJ0Eq3rIDLKG33r"; // example salt used in blog post
    $salt = base64_decode($salt_base64);
    $hash = hash("sha512", $password.$salt, true);
    $hash = hash("sha512", $password . $salt, true);
    $hash_base64 = base64_encode($hash);
    return($username.":$6$".$salt_base64."$".$hash_base64);
}
?>