The correct way to fix apt-get warning “Key is stored in legacy trusted.gpg keyring” in Debian and Ubuntu

If you used a PPA or added an external repository in Debian 11, Ubuntu 22.04, chances are that you recently have been seeing a message like this every time you run apt-get:

W: https://{{some_reporsitory_url}}: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.

This is a warning that apt-key is printing out. The tool has been used to mange the list of keys used by apt to authenticate packages. Packages which have been authenticated using these keys will be considered trusted.

Back to the warning… the reason behind the warning is clear: apt-key is deprecated and will last be available in Debian 11 and Ubuntu 22.04.

There are several answers on stackoverflow.com, askubuntu.com, stackexchange.com and other similar sites, as well as on several blogs, where authors suggest exporting the keys from /etc/apt/trusted.gpg to /etc/apt/trusted.gpg.d/repository_keyring.gpg. However, the result will be that the keys in that folders will be used to authenticate any repository, which is the exact reason why apt-key got deprecated in the first place.

According to the apt-key documentation, here is the correct way to deal with this issue (quote):

If you read the recommendation, it states that the goal is to place the keys in contrast with blogs posts and answers circulating online, anywhere on the filesystem but /etc/apt/trusted.gpg.d/. That is very explicit.

For this How-To guide we will use /etc/apt/keyrings/

Let’s start!

First we find the offending key(s):

apt-key --keyring /etc/apt/trusted.gpg list 2>/dev/null |
grep -A 1 "pub " |grep -v "pub " | grep -v '\-\-' | awk -v OFS="" '{$1=$1}1'

This is just a fancy way to get the list of keys in /etc/apt/trusted.gpg. Now for every {key} let’s do the following:

apt-key --keyring /etc/apt/trusted.gpg export {key} | gpg --dearmor -o /etc/apt/keyrings/{{key}}.gpg

The next step is to reference the {{key}} in the related {{repository}}. Now we should edit /etc/apt/sources.list.d/{{repository}} and add [singed-by=/etc/apt/keyrings/{{key}}.gpg] between deb and the url that usually follows

deb [singed-by=/etc/apt/keyrings/{{key}}.gpg] {{repository_url}} {{release}} {{package}}