Generating GPG Key Files

Joaquín Menchaca (智裕)
2 min readFeb 27, 2018

At some point, you may have to generate a pair of GPG keys for use with signing packages, like Debian packages. You may want to create a public repository for your packages, or a mirror, either various Debian tools or automate the process with Aptly.

For this process to work, you need to have a private key stored on the server, and the clients will need a public key.

But how to you automate this process?

Prerequisite for Virtual Machines

On virtual Ubuntu systems, you can use RNG for quality random numbers. This will actually be required:

sudo apt-get install -y rng-tools
sudo rngd -r /dev/urandom

Automating GPG

For automating GPG, you can create generate keys using the following method. Toggle the values for the keys to best match your needs. This should be adequate

cat << EOF > gpg_batch
%echo Generating a GPG key, might take a while
Key-Type: RSA
Key-Length: 2048
Subkey-Type: RSA
Subkey-Length: 2048
Name-Real: MyCompany Ops Department
Name-Comment: Repo Signing
Name-Email: ops@mycompany.com
Expire-Date: 0
%pubring igg_aptly.pub
%secring igg_aptly.sec
%commit
%echo done
EOF
gpg --batch --gen-key gpg_batch

Installing Keys with Change Configuration

After you get this keys, you may want to convert them to ASCII so that you can use them perhaps in a change configuration system, like Chef encrypted data bags, Ansible vaulted variables, Puppet Encrypted Hiera, etc.

For this process you can do the following:

gpg --no-default-keyring --armor \
--secret-keyring ./repo_key.sec \
--keyring ./repo_key.pub \
--export ops@mycompany.com > repo_key.pub.asc
gpg --no-default-keyring --armor \
--secret-keyring ./repo_key.sec \
--keyring ./repo_key.pub \
--export-secret-key ops@mycompany.com > repo_key.sec.asc

Now you have the actual keys in naked clear text file — something rather dangerous!

You may need to convert these in to a single line. You can do this using sed:

sed ':a;N;$!ba;s/\n/\\n/g' repo_key.pub.asc
sed ':a;N;$!ba;s/\n/\\n/g' repo_key.sec.asc

With these, you can now store these encrypted strings in your git repo, in the format used by your preferred change configuration platform, e.g. encrypted data bags, encrypted variable yaml files, or encrypted hiera files.

--

--