Skip to content

Commit

Permalink
Hash password for generating client id for mqtt clients
Browse files Browse the repository at this point in the history
Fixes #2653
  • Loading branch information
ozangunalp committed Jul 5, 2024
1 parent fc220db commit 16a67f7
Showing 1 changed file with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import static io.smallrye.reactive.messaging.mqtt.i18n.MqttLogging.log;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

Expand All @@ -21,16 +25,44 @@ private Clients() {
// avoid direct instantiation.
}

private static String sha512(String password) {
if (password == null || password.isEmpty()) {
return null;
}
MessageDigest messageDigest = getMessageDigest("SHA-512");
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
messageDigest.update(salt);
StringBuilder sb = new StringBuilder();
toHex(messageDigest.digest(password.getBytes(StandardCharsets.UTF_8)), sb);
return sb.toString();
}

private static void toHex(byte[] digest, StringBuilder sb) {
for (byte b : digest) {
sb.append(Integer.toHexString((b & 0xFF) | 0x100), 1, 3);
}
}

private static MessageDigest getMessageDigest(String alg) {
try {
return MessageDigest.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
}

static ClientHolder getHolder(Vertx vertx, MqttClientSessionOptions options) {

String host = options.getHostname();
int port = options.getPort();
String clientId = options.getClientId();
String server = options.getServerName().orElse(null);
String username = options.getUsername();
String password = options.getPassword();
String pwdDigest = sha512(options.getPassword());

String id = username + ":" + password + "@"
String id = username + ":" + pwdDigest + "@"
+ host + ":"
+ port
+ "<" + (server == null ? "" : server)
Expand Down

0 comments on commit 16a67f7

Please sign in to comment.