~mikini/hometools

a7feff95a84e43af4fcde4993730725b25559aef — Mikkel Kirkgaard Nielsen 10 months ago 915ac40
Add PHP script for gen. mosquitto_passwd compatible auth tokens

Refer to blog post;
https://mikini.dk/2017/01/generating-passwords-for-mosquitto-mqtt-broker-using-php
1 files changed, 30 insertions(+), 0 deletions(-)

A mosquitto_passwd.php
A mosquitto_passwd.php => mosquitto_passwd.php +30 -0
@@ 0,0 1,30 @@
#! /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
// mosquitto_passwd utility (mosquitto_passwd(1),
// https://mosquitto.org/man/mosquitto_passwd-1.html).

// Based on a question & thread in the Mosquitto mailing list, see blog post;
// 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");
}
else {
    echo("ERROR: Supply username and password as arguments in that order.\n");
}

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_base64 = base64_encode($hash);
    return($username.":$6$".$salt_base64."$".$hash_base64);
}
?>