Solution for Linux apt-get "KEYEXPIRED - The following signatures were invalid"

Sometimes keys get old on a server you’ve had up for a while. We just need to update those third party keys. When you get something like:

Failed to fetch http://repo.mongodb.org/apt/ubuntu/dists/xenial/mongodb-org/3.2/Release.gpg  The following signatures were invalid KEYEXPIRED 1570654450

in your shell, we simply need to renew each individual key.

Step 1: Find the Expired Key

First, run sudo apt-key list | grep -A 1 expired to print a list of all the installed keys on your server. It’ll output something like:

pub   4096R/EA312927 2015-10-09 [expired: 2019-10-09]
uid                  MongoDB 3.2 Release Signing Key <packaging@mongodb.com>
--
pub   4096R/A15703C6 2016-01-11 [expired: 2018-01-10]
uid                  MongoDB 3.4 Release Signing Key <packaging@mongodb.com>

The ID we’d need comes after the 4096R part. So in the above example, EA312927 & A15703C6 are the IDs we need for the next part.

Step 2: Renew the Expired Key

Now we’re going to renew the keys with the IDs we have from the previous step. We’re going to run the following commands for the two keys listed above. Notice the IDs at the end.

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EA312927
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys A15703C6

Output should be:

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EA312927
Executing: /tmp/tmp.JAJVfssi3i/gpg.1.sh --keyserver
hkp://keyserver.ubuntu.com:80
--recv-keys
EA312927
gpg: requesting key EA312927 from hkp server keyserver.ubuntu.com
gpg: key EA312927: "Totally Legit Signing Key <mallory@example.org>" not changed
gpg: Total number processed: 1
gpg:              unchanged: 1

and the second one:

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys A15703C6
Executing: /tmp/tmp.tIzpWbn6MI/gpg.1.sh --keyserver
hkp://keyserver.ubuntu.com:80
--recv-keys
A15703C6
gpg: requesting key A15703C6 from hkp server keyserver.ubuntu.com
gpg: key A15703C6: "MongoDB 3.4 Release Signing Key <packaging@mongodb.com>" 2 new signatures
gpg: Total number processed: 1
gpg:         new signatures: 2

Step 3: Profit. J/k, Update Time

At this point we should be able to now update safely. To finish, just run:

sudo apt-get update

Your Linux install will now update with the latest packages as expected.

Last Resort

Got a stubborn key that won’t update? Remove it like so:

sudo apt-key del A15703C6

Update all the expired keys from Ubuntu key server in one command:

sudo apt-key list | \
 grep "expired: " | \
 sed -ne 's|pub .*/\([^ ]*\) .*|\1|gp' | \
 xargs -n1 sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys
ender