[Home](https://codefionn.eu/) · [About](https://codefionn.eu/about/) · [GitHub](https://github.com/codefionn)

---

# Encrypted mosquitto server

> Setting up an encrypted mosquitto server with a self-signed certificate

*Published on 2023-04-16 · [View as HTML](https://codefionn.eu/encrypted-mosquitto-server/)*

---


Below, certificates and keys will be created for
<abbr title="Transport Layer Security">TLS</abbr>. Then the misquitto
configuration will be edited. Your server will run on `localhost:8883` afterwards
not `localhost:1883`.

## Create directory for certificates

```bash
mkdir /etc/mosquitto/certs
cd /etc/mosquitto/certs
```

## Create CA Key

Using password protection and 4096-bit RSA.

```bash
openssl genrsa -des3 -out m2mqtt_ca.key 4096
Create CA Certificate
openssl req -new -x509 -days 9000 -key m2mqtt_ca.key -out m2mqtt_ca.crt
```

## Create Server Key

Using no password and 4096-bit RSA.

```bash
openssl genrsa -out m2mqtt_srv.key 4096
```

## Create Server Sign Request

```bash
openssl req -new -out m2mqtt_srv.csr -key m2mqtt_srv.key -subj '/CN=localhost'
```

## Create domain configuration domain.ext

This is important, so the domain and certificate can be validated.

```bash
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
IP.2 = ::1
```

With cool command line stuff this is:

```bash
cat > domain.ext << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
IP.2 = ::1
EOF
```

## Create Server Certificate

```bash
openssl x509 -req -CA m2mqtt_ca.crt -CAkey m2mqtt_ca.key \
  -in m2mqtt_srv.csr -out m2mqtt_srv.crt \
  -days 9000 -CAcreateserial -extfile domain.ext
```

## Edit /etc/mosquitto/mosquitto.conf

Uncomment line with setting listener and add the following at the end of the
line:

```bash
8883
```

Uncomment line with setting cafile and add the following at the end of the line:

```bash
/etc/mosquitto/certs/m2mqtt_ca.crt
```

Uncomment line with setting certfile and add the following at the end of the
line:

```bash
/etc/mosquitto/certs/m2mqtt_srv.crt
```

Uncomment line with setting keyfile and add the following at the end of the
line:

```bash
/etc/mosquitto/certs/m2mqtt_srv.key
```

These should be all changes you made just now:

```bash
listener 8883
cafile /etc/mosquitto/certs/m2mqtt_ca.crt
certfile /etc/mosquitto/certs/m2mqtt_srv.crt
keyfile /etc/mosquitto/certs/m2mqtt_srv.key
```

Don't forget to add the CAfile m2mqtt\_ca.crt to your MQTT client!

## Restart the mosquitto server

```bash
service mosquitto restart
```

---

[Impressum](https://codefionn.eu/impressum/) · [Datenschutzerklärung](https://codefionn.eu/datenschutz/) · [Mastodon](https://c.im/@codefionn)

© Copyright 2022-2026 Fionn Langhans
