This is a guide to using YubiKey as a smart card for secure encryption, signature and authentication operations.
Cryptographic keys on YubiKey are non-exportable, unlike filesystem-based credentials, while remaining convenient for regular use. YubiKey can be configured to require a physical touch for cryptographic operations, reducing the risk of unauthorized access.
- Purchase YubiKey
- Prepare environment
- Install software
- Prepare GnuPG
- Create Certify key
- Create Subkeys
- Verify keys
- Backup keys
- Export public key
- Configure YubiKey
- Transfer Subkeys
- Verify transfer
- Finish setup
- Using YubiKey
- Updating keys
- Reset YubiKey
- Optional hardening
- Notes
- Troubleshooting
- Alternative solutions
- Additional resources
All YubiKeys except FIDO-only Security Key Series and Bio Series YubiKeys are compatible with this guide.
Verify YubiKey by visiting yubico.com/genuine. Select Verify Device to begin the process. Touch the YubiKey when prompted and allow the site to see the make and model of the device when prompted. This device attestation may help mitigate supply chain attacks.
Several portable storage devices (such as microSD cards) for storing encrypted backups are also recommended.
A dedicated, secure operating environment is recommended to generate cryptographic keys.
The following is a general ranking of environments least to most hospitable to generating materials:
- Public, shared or other computer owned by someone else
- Daily-use personal operating system with unrestricted network access
- Virtualized operating system with limited capabilities (using virt-manager, VirtualBox or VMware, for example)
- Dedicated and hardened Debian or OpenBSD installation
- Ephemeral Debian Live or Tails booted without primary storage attached
- Hardened hardware and firmware (e.g., Coreboot, Intel ME removed)
- Air-gapped system without network capabilities, preferably ARM-based Raspberry Pi or other architecturally diverse equivalent
Debian Live is used in this guide to balance usability and security, with some additional instructions for OpenBSD.
Download the latest Debian Live image and signature files:
export IMAGE_URL="https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/"
curl -fLO "$IMAGE_URL/SHA512SUMS" -O "$IMAGE_URL/SHA512SUMS.sign"
curl -fLO "$IMAGE_URL/$(awk '/xfce.iso$/ {print $2}' SHA512SUMS)"Download the Debian signing public key:
gpg --keyserver hkps://keyring.debian.org \
--recv DF9B9C49EAA9298432589D76DA87E80D6294BE9BIf the public key cannot be received, use a different keyserver or DNS server:
gpg --keyserver hkps://keyserver.ubuntu.com:443 \
--recv DF9B9C49EAA9298432589D76DA87E80D6294BE9BThe Debian Live signing public key is also available for import in pubkeys:
gpg --import pubkeys/debian-DA87E80D6294BE9B.ascVerify the signature:
gpg --verify SHA512SUMS.sign SHA512SUMSgpg: Good signature from "Debian CD signing key <[email protected]>" must appear in the output.
Verify the cryptographic hash of the image file matches the one in the signed file:
grep $(sha512sum debian-live-*-amd64-xfce.iso) SHA512SUMSSee Verifying authenticity of Debian CDs for more information.
Connect a portable storage device and identify the disk label - this guide uses /dev/sdc throughout, but this value may differ on your system:
Linux
$ sudo dmesg | tail
usb-storage 3-2:1.0: USB Mass Storage device detected
sd 2:0:0:0: [sdc] Attached SCSI removable diskCopy the Debian image to the device:
sudo dd if=debian-live-*-amd64-xfce.iso of=/dev/sdc bs=4M status=progress ; syncOpenBSD
$ dmesg | tail -n2
sd2 at scsibus4 targ 1 lun 0: <TS-RDF5, SD Transcend, TS3A> SCSI4 0/direct removable serial.0000000000000
sd2: 15193MB, 512 bytes/sector, 31116288 sectors
$ doas dd if=debian-live-*-amd64-xfce.iso of=/dev/rsd2c bs=4m
465+1 records in
465+1 records out
1951432704 bytes transferred in 139.125 secs (14026448 bytes/sec)Power off, remove internal hard drives and all unnecessary devices, such as the wireless card.
Load the operating system and configure networking. Optional hardening steps related to networking can be found below.
Tip
If the screen locks on Debian Live, unlock with user / live
Open terminal and install required software packages.
Debian/Ubuntu
sudo apt update
sudo apt -y upgrade
sudo apt -y install \
wget gnupg2 gnupg-agent dirmngr \
cryptsetup scdaemon pcscd \
yubikey-personalization yubikey-managerOpenBSD
doas pkg_add gnupg pcsc-toolsmacOS
Download and install Homebrew and the following packages:
brew install \
gnupg yubikey-personalization ykman pinentry-mac wgetNote
An additional Python package dependency may need to be installed to use ykman - pip install yubikey-manager
Or using MacPorts, install the following packages:
sudo port install gnupg2 yubikey-manager pinentry wgetNixOS
Build an air-gapped NixOS LiveCD image:
ref=$(git ls-remote https://github.com/drduh/Yubikey-Guide refs/heads/master | awk '{print $1}')
nix build --experimental-features "nix-command flakes" \
github:drduh/YubiKey-Guide/$ref#nixosConfigurations.yubikeyLive.x86_64-linux.config.system.build.isoImageIf you have this repository checked out:
Recommended, but optional: update nixpkgs and drduh/config:
nix flake update --commit-lock-fileBuild the image:
nix build --experimental-features "nix-command flakes" .#nixosConfigurations.yubikeyLive.x86_64-linux.config.system.build.isoImageCopy to USB drive:
sudo cp -v result/iso/yubikeyLive.iso /dev/sdc ; syncSkip steps to create a temporary working directory and a hardened configuration, as they are already part of the image.
Test builds using virtualization tools like QEMU. Keep in mind a virtualized environment does not provide the same amount of security as an ephemeral system (see Prepare environment above).
Here is an example QEMU invocation after placing yubikeyLive in result/iso using the above nix build command:
# Launch with 4G memory, 2 CPUs and KVM enabled
qemu-system-x86_64 \
-enable-kvm \
-m 4G \
-smp 2 \
-drive readonly=on,media=cdrom,format=raw,file=result/iso/yubikeyLive.isoArch
sudo pacman -Syu --needed gnupg pcsclite ccid yubikey-personalizationRHEL7
sudo yum install -y gnupg2 pinentry-curses pcsc-lite pcsc-lite-libs gnupg2-smimeFedora
sudo dnf install \
wget gnupg2 \
cryptsetup pcsc-lite \
yubikey-personalization-gui yubikey-managerCreate a temporary directory which will be cleared on reboot and set it as the GnuPG directory:
export GNUPGHOME=$(mktemp -d -t $(date +%Y.%m.%d)-XXXX)Create or import a hardened configuration:
cd $GNUPGHOME
wget https://raw.githubusercontent.com/drduh/YubiKey-Guide/master/config/gpg.confThe options will look similar to:
$ grep -v "^#" $GNUPGHOME/gpg.conf
personal-cipher-preferences AES256 AES192 AES
personal-digest-preferences SHA512 SHA384 SHA256
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
cert-digest-algo SHA512
s2k-digest-algo SHA512
s2k-cipher-algo AES256
charset utf-8
no-comments
no-emit-version
no-greeting
keyid-format 0xlong
list-options show-uid-validity
verify-options show-uid-validity
with-fingerprint
require-cross-certification
require-secmem
no-symkey-cache
armor
use-agent
throw-keyidsImportant
Networking should be disabled for the remainder of the setup.
When creating an identity with GnuPG, the default options ask for a "Real name", "Email address" and optional "Comment".
Depending on how you plan to use GnuPG, set these values respectively1:
export IDENTITY="YubiKey User <[email protected]>"Or use any attribute which will uniquely identity the key (this may be incompatible with certain use cases):
export IDENTITY="My Cool YubiKey - 2025"Set the algorithm and key size - RSA/4096 is recommended:
export KEY_TYPE=rsa4096Determine the desired Subkey validity duration.
Setting a Subkey expiry forces identity and credential lifecycle management. However, setting an expiry on the Certify key is pointless, because it can just be used to extend itself2.
This guide recommends a two year expiration for Subkeys to balance security and usability, however longer durations are possible to reduce maintenance frequency.
When Subkeys expire, they may still be used to decrypt with GnuPG and authenticate with SSH, however they can not be used to encrypt nor sign new messages.
Subkeys must be renewed or rotated using the Certify key - see Updating keys.
Set Subkeys to expire on a planned date:
export EXPIRATION=2027-07-01The expiration date may also be relative, for example set to two years from today:
export EXPIRATION=2yGenerate a passphrase for the Certify key. This credential will be used to manage identity Subkeys.
To improve readability, this guide recommends a passphrase consisting only of uppercase letters and numbers.
The following commands will generate a strong3 passphrase while avoiding certain similar-looking characters:
export CERTIFY_PASS=$(LC_ALL=C tr -dc "A-Z2-9" < /dev/urandom | \
tr -d "IOUS5" | \
fold -w ${PASS_GROUPSIZE:-4} | \
paste -sd ${PASS_DELIMITER:--} - | \
head -c ${PASS_LENGTH:-29})
printf "\n$CERTIFY_PASS\n\n"To change the passphrase length, delimiting character or group sizes, export the respective variable(s) prior to running the passphrase generation command, for example:
export PASS_GROUPSIZE=6
export PASS_DELIMITER=+
export PASS_LENGTH=48Write the passphrase in a secure location - separate from the portable storage device used for key material, or memorize it.
This repository includes a passphrase.html template to help with credential transcription. Save the raw file, open in a browser to render and print.
Mark the corresponding character on sequential rows for each character in the passphrase. passphrase.txt can also be printed without a browser:
lp -d Printer-Name passphrase.txtDiceware is another popular method for creating memorable passphrases.
The primary key to generate is the Certify key, which is responsible for issuing Subkeys for encryption, signature and authentication operations.
The Certify key should be kept offline at all times and only accessed from a dedicated and secure environment to issue or revoke Subkeys.
Do not set an expiration date on the Certify key.
Generate the Certify key:
echo "$CERTIFY_PASS" | \
gpg --batch --passphrase-fd 0 \
--quick-generate-key "$IDENTITY" "$KEY_TYPE" cert neverSet and view the Certify key identifier and fingerprint for use later:
export KEYID=$(gpg -k --with-colons "$IDENTITY" | \
awk -F: '/^pub:/ { print $5; exit }')
export KEYFP=$(gpg -k --with-colons "$IDENTITY" | \
awk -F: '/^fpr:/ { print $10; exit }')
printf "\nKey ID/Fingerprint: %20s\n%s\n\n" "$KEYID" "$KEYFP"Add additional IDs (optional)
This is an optional step for use cases requiring additional identities, for example:
- different email addresses for different languages
- different email addresses for professional versus personal but please see alternative reason below for not tying these addresses together
- anonymized email addresses for different git providers
An alternative would be to have distinct keys but you would then require multiple YubiKeys, as each can only hold a single key for each type (signing, encryption, authentication). Nevertheless, there can be good reasons to have multiple YubiKeys:
- if you have different email addresses for professional versus personal use cases, having distinct keys allow you to disassociate the identities
- if you are also using the YubiKey as a U2F or FIDO2 device, having multiple YubiKeys is generally recommended as a backup measure
Define an array containing additional user IDs. Each array element must be wrapped in quotes and each element must be space-delimited:
declare -a additional_uids
additional_uids=("Super Cool YubiKey 2025" "uid 1 <[email protected]>")Add the additional user IDs to the Certify key:
for uid in "${additional_uids[@]}" ; do \
echo "$CERTIFY_PASS" | \
gpg --batch --passphrase-fd 0 \
--pinentry-mode=loopback --quick-add-uid "$KEYFP" "$uid"
doneAdjust the trust of the additional IDs to ultimate:
gpg --command-fd=0 --pinentry-mode=loopback --edit-key "$KEYID" <<EOF
uid *
trust
5
y
save
EOFGenerate Signature and Encryption Subkeys using the previously configured key type, passphrase and expiration:
echo "$CERTIFY_PASS" | \
gpg --batch --pinentry-mode=loopback --passphrase-fd 0 \
--quick-add-key "$KEYFP" "$KEY_TYPE" sign "$EXPIRATION"
echo "$CERTIFY_PASS" | \
gpg --batch --pinentry-mode=loopback --passphrase-fd 0 \
--quick-add-key "$KEYFP" "$KEY_TYPE" encrypt "$EXPIRATION"Followed by the Authentication Subkey:
Note
Some systems no longer accept RSA for SSH authentication; to use Ed25519, set the KEY_TYPE variable to ed25519 before generating Authentication Subkey.
echo "$CERTIFY_PASS" | \
gpg --batch --pinentry-mode=loopback --passphrase-fd 0 \
--quick-add-key "$KEYFP" "$KEY_TYPE" auth "$EXPIRATION"
List available secret keys:
gpg -KThe output will display [C]ertify, [S]ignature, [E]ncryption and [A]uthentication keys:
sec rsa4096/0xF0F2CFEB04341FB5 2025-07-01 [C]
Key fingerprint = 4E2C 1FA3 372C BA96 A06A C34A F0F2 CFEB 0434 1FB5
uid [ultimate] YubiKey User <yubikey@example>
ssb rsa4096/0xB3CD10E502E19637 2025-07-01 [S] [expires: 2027-07-01]
ssb rsa4096/0x30CBE8C4B085B9F7 2025-07-01 [E] [expires: 2027-07-01]
ssb rsa4096/0xAD9E24E1B8CB9600 2025-07-01 [A] [expires: 2027-07-01]Save a copy of the Certify key, Subkeys and public key:
echo "$CERTIFY_PASS" | \
gpg --output $GNUPGHOME/$KEYID-Certify.key \
--batch --pinentry-mode=loopback --passphrase-fd 0 \
--armor --export-secret-keys $KEYID
echo "$CERTIFY_PASS" | \
gpg --output $GNUPGHOME/$KEYID-Subkeys.key \
--batch --pinentry-mode=loopback --passphrase-fd 0 \
--armor --export-secret-subkeys $KEYID
gpg --output $GNUPGHOME/$KEYID-$(date +%F).asc \
--armor --export $KEYIDCreate an encrypted backup on portable storage to be kept offline in a secure and durable location.
The following process is recommended to be repeated several times on multiple portable storage devices, as they are likely to fail over time. As an additional backup measure, Paperkey can be used to make a physical copy of key materials for improved durability.
Tip
ext2 volumes (without encryption) can be mounted on Linux and OpenBSD. Use FAT32 or NTFS volumes for macOS and Windows compatibility instead.
Linux
Attach a portable storage device and check its label, in this case /dev/sdc:
$ sudo dmesg | tail
usb-storage 3-2:1.0: USB Mass Storage device detected
sd 2:0:0:0: [sdc] Attached SCSI removable disk
$ sudo fdisk -l /dev/sdc
Disk /dev/sdc: 14.9 GiB, 15931539456 bytes, 31116288 sectorsCaution
Confirm the destination (of) before issuing the following command - it is destructive! This guide uses /dev/sdc throughout, but this value may be different on your system.
Zero the header to prepare for encryption:
sudo dd if=/dev/zero of=/dev/sdc bs=4M count=1Remove and re-connect the storage device.
Erase and create a new partition table:
sudo fdisk /dev/sdc <<EOF
g
w
EOFCreate a small (at least 20 Mb is recommended to account for the LUKS header size) partition for storing secret materials:
sudo fdisk /dev/sdc <<EOF
n
+20M
w
EOFUse LUKS to encrypt the new partition.
Generate another unique Passphrase (ideally different from the one used for the Certify key) to protect the encrypted volume:
export LUKS_PASS=$(LC_ALL=C tr -dc "A-Z2-9" < /dev/urandom | \
tr -d "IOUS5" | \
fold -w ${PASS_GROUPSIZE:-4} | \
paste -sd ${PASS_DELIMITER:--} - | \
head -c ${PASS_LENGTH:-29})
printf "\n$LUKS_PASS\n\n"This passphrase will also be used infrequently to access the Certify key and should be very strong.
Write the passphrase down or memorize it.
Format the partition:
echo $LUKS_PASS | \
sudo cryptsetup -q luksFormat /dev/sdc1Mount the partition:
echo $LUKS_PASS | \
sudo cryptsetup -q luksOpen /dev/sdc1 gnupg-secretsCreate an ext2 filesystem:
sudo mkfs.ext2 /dev/mapper/gnupg-secrets -L gnupg-$(date +%F)Mount the filesystem and copy the temporary GnuPG working directory with key materials:
sudo mkdir /mnt/encrypted-storage
sudo mount /dev/mapper/gnupg-secrets /mnt/encrypted-storage
sudo cp -av $GNUPGHOME /mnt/encrypted-storage/Unmount and close the encrypted volume:
sudo umount /mnt/encrypted-storage
sudo cryptsetup luksClose gnupg-secretsRepeat the process for any additional storage devices (at least two are recommended).
OpenBSD
Attach a USB disk and determine its label:
$ dmesg | grep sd.\ at
sd2 at scsibus5 targ 1 lun 0: <TS-RDF5, SD Transcend, TS37> SCSI4 0/direct removable serial.00000000000000000000Print the existing partitions to make sure it's the right device:
doas disklabel -h sd2Initialize the disk by creating an a partition with FS type RAID and size of 25 Megabytes:
$ doas fdisk -giy sd2
Writing MBR at offset 0.
Writing GPT.
$ doas disklabel -E sd2
Label editor (enter '?' for help at any prompt)
sd2> a a
offset: [64]
size: [31101776] 25M
FS type: [4.2BSD] RAID
sd2*> w
sd2> q
No label changesEncrypt with bioctl using a unique Passphrase:
$ doas bioctl -c C -l sd2a softraid0
New passphrase:
Re-type passphrase:
softraid0: CRYPTO volume attached as sd3Create an i partition on the new crypto volume and the filesystem:
$ doas fdisk -giy sd3
Writing MBR at offset 0.
Writing GPT.
$ doas disklabel -E sd3
Label editor (enter '?' for help at any prompt)
sd3> a i
offset: [64]
size: [16001]
FS type: [4.2BSD]
sd3*> w
sd3> q
No label changes.
$ doas newfs sd3iMount the filesystem and copy the temporary directory with the keyring:
doas mkdir /mnt/encrypted-storage
doas mount /dev/sd3i /mnt/encrypted-storage
doas cp -av $GNUPGHOME /mnt/encrypted-storageUnmount and remove the encrypted volume:
doas umount /mnt/encrypted-storage
doas bioctl -d sd3See OpenBSD FAQ#14 for more information.
Important
Without the public key, it will not be possible to use GnuPG to decrypt/sign messages. However, YubiKey can still be used for SSH authentication.
Connect another portable storage device or create a new partition on the existing one.
Linux
Using the same /dev/sdc device as in the previous step, create a small (at least 20 Mb is recommended) partition for storing materials:
sudo fdisk /dev/sdc <<EOF
n
+20M
w
EOFCreate a filesystem and export the public key:
sudo mkfs.ext2 /dev/sdc2
sudo mkdir /mnt/public
sudo mount /dev/sdc2 /mnt/public
gpg --armor --export $KEYID | sudo tee /mnt/public/$KEYID-$(date +%F).asc
sudo chmod 0444 /mnt/public/*.ascUnmount and remove the storage device:
sudo umount /mnt/publicOpenBSD
$ doas disklabel -E sd2
Label editor (enter '?' for help at any prompt)
sd2> a b
offset: [32130]
size: [31069710] 25M
FS type: [swap] 4.2BSD
sd2*> w
sd2> q
No label changes.Create a filesystem and export the public key to it:
doas newfs sd2b
doas mkdir /mnt/public
doas mount /dev/sd2b /mnt/public
gpg --armor --export $KEYID | doas tee /mnt/public/$KEYID-$(date +%F).ascUnmount and remove the storage device:
doas umount /mnt/publicConnect YubiKey and confirm its status:
gpg --card-statusIf the YubiKey is locked, Reset it.
YubiKey's PGP interface has its own PINs separate from other modules such as PIV:
| Name | Default | Capability |
|---|---|---|
| User PIN | 123456 |
cryptographic operations (decrypt, sign, authenticate) |
| Admin PIN | 12345678 |
reset PIN, change Reset Code, add keys and owner information |
| Reset Code | None | reset PIN (more information) |
Determine the desired PIN values. They can be shorter than the Certify key passphrase due to limited brute-forcing opportunities; the User PIN should be convenient enough to remember for every-day use.
The User PIN must be at least 6 characters and the Admin PIN must be at least 8 characters. A maximum of 127 ASCII characters are allowed. See Managing PINs for more information.
Set PIN values, for example a 6 digit User PIN and 8 digit Admin PIN:
export ADMIN_PIN=$(LC_ALL=C tr -dc '0-9' < /dev/urandom | \
fold -w8 | head -1)
export USER_PIN=$(LC_ALL=C tr -dc '0-9' < /dev/urandom | \
fold -w6 | head -1)
printf "\nAdmin PIN: %12s\nUser PIN: %13s\n\n" \
"$ADMIN_PIN" "$USER_PIN"Change the Admin PIN:
gpg --command-fd=0 --pinentry-mode=loopback --change-pin <<EOF
3
12345678
$ADMIN_PIN
$ADMIN_PIN
q
EOFChange the User PIN:
gpg --command-fd=0 --pinentry-mode=loopback --change-pin <<EOF
1
123456
$USER_PIN
$USER_PIN
q
EOFRemove and re-insert YubiKey.
Caution
Three incorrect User PIN entries will cause it to become blocked and must be unblocked with either the Admin PIN or Reset Code. Three incorrect Admin PIN or Reset Code entries will destroy data on YubiKey.
The number of retry attempts can be changed, for example to 5 attempts:
ykman openpgp access set-retries 5 5 5 -f -a $ADMIN_PINUse previously set values:
gpg --command-fd=0 --pinentry-mode=loopback --edit-card <<EOF
admin
login
$IDENTITY
$ADMIN_PIN
quit
EOFSmart card attributes can also be set with gpg --edit-card and admin mode. Use help to see available options. The login attribute is required.
Run gpg --card-status to verify results (Login data field).
Important
Transferring keys to YubiKey converts the on-disk key into a "stub" - making it no longer usable to transfer to subsequent YubiKeys. Ensure keys were backed up before proceeding.
The Certify key passphrase and Admin PIN are required to transfer keys.
Transfer the Signature key:
gpg --command-fd=0 --pinentry-mode=loopback --edit-key $KEYID <<EOF
key 1
keytocard
1
$CERTIFY_PASS
$ADMIN_PIN
save
EOFRepeat the process for the Encryption key:
gpg --command-fd=0 --pinentry-mode=loopback --edit-key $KEYID <<EOF
key 2
keytocard
2
$CERTIFY_PASS
$ADMIN_PIN
save
EOFRepeat the process for the Authentication key:
gpg --command-fd=0 --pinentry-mode=loopback --edit-key $KEYID <<EOF
key 3
keytocard
3
$CERTIFY_PASS
$ADMIN_PIN
save
EOFVerify Subkeys are on YubiKey with gpg -K - indicated by ssb>:
sec rsa4096/0xF0F2CFEB04341FB5 2025-07-01 [C]
Key fingerprint = 4E2C 1FA3 372C BA96 A06A C34A F0F2 CFEB 0434 1FB5
uid [ultimate] YubiKey User <yubikey@example>
ssb> rsa4096/0xB3CD10E502E19637 2025-07-01 [S] [expires: 2027-07-01]
ssb> rsa4096/0x30CBE8C4B085B9F7 2025-07-01 [E] [expires: 2027-07-01]
ssb> rsa4096/0xAD9E24E1B8CB9600 2025-07-01 [A] [expires: 2027-07-01]The > after a tag indicates the key is stored on a smart card.
Verify the following steps were performed correctly:
- Memorized or wrote down the Certify key (identity) passphrase to a secure and durable location
echo $CERTIFY_PASSto see it again;passphrase.htmlorpassphrase.txtto transcribe it
- Memorized or wrote down passphrase to encrypted volume on portable storage
echo $LUKS_PASSto see it again;passphrase.htmlorpassphrase.txtto transcribe it
- Saved the Certify key and Subkeys to encrypted portable storage, to be kept offline
- At least two backups are recommended, stored at separate locations
- Exported a copy of the public key where is can be easily accessed later
- Separate device or non-encrypted partition was used
- Memorized or wrote down the User PIN and Admin PIN, which are unique and changed from default values
echo $USER_PIN $ADMIN_PINto see them again;passphrase.htmlorpassphrase.txtto transcribe them
- Moved Encryption, Signature and Authentication Subkeys to YubiKey
gpg -Kshowsssb>for each of the 3 Subkeys
Reboot, clearing the ephemeral environment, to complete setup.
Initialize GnuPG:
gpg -kCreate or import a hardened configuration:
cd ~/.gnupg
wget https://raw.githubusercontent.com/drduh/YubiKey-Guide/master/config/gpg.confSet the following option. This avoids the problem where GnuPG will repeatedly prompt for the insertion of an already-inserted YubiKey:
touch scdaemon.conf
echo "disable-ccid" >>scdaemon.confInstall the required packages:
Debian/Ubuntu
sudo apt update
sudo apt install -y gnupg gnupg-agent scdaemon pcscdArch
sudo pacman -S --needed gnupg pcsc-tools
sudo systemctl enable --now pcscd.servicemacOS
brew install gnupgOr using MacPorts
sudo port install gnupg2 pcsc-toolsOpenBSD
doas pkg_add gnupg pcsc-tools
doas rcctl enable pcscd
doas rebootMount the non-encrypted volume with the public key:
Debian/Ubuntu
sudo mkdir /mnt/public
sudo mount /dev/sdc2 /mnt/publicOpenBSD
doas mkdir /mnt/public
doas mount /dev/sd3i /mnt/publicImport the public key:
gpg --import /mnt/public/*.ascOr download the public key from a keyserver:
gpg --recv $KEYIDOr with the URL on YubiKey, retrieve the public key using the command gpg --edit-card.
gpg/card> fetch
gpg/card> quitDetermine the key ID:
gpg -k
export KEYID=0xF0F2CFEB04341FB5Assign ultimate trust by typing trust and selecting option 5 then quit:
gpg --command-fd=0 --pinentry-mode=loopback --edit-key $KEYID <<EOF
trust
5
y
save
EOFRemove and re-insert YubiKey.
Verify the status with gpg --card-status which will list the available Subkeys:
Reader ...........: Yubico YubiKey OTP FIDO CCID 00 00
Application ID ...: D2760001240102010006055532110000
Application type .: OpenPGP
Version ..........: 3.4
Manufacturer .....: Yubico
Serial number ....: 05553211
Name of cardholder: YubiKey User
Language prefs ...: en
Salutation .......:
URL of public key : [not set]
Login data .......: yubikey@example
Signature PIN ....: not forced
Key attributes ...: rsa4096 rsa4096 rsa4096
Max. PIN lengths .: 127 127 127
PIN retry counter : 3 3 3
Signature counter : 0
KDF setting ......: on
Signature key ....: CF5A 305B 808B 7A0F 230D A064 B3CD 10E5 02E1 9637
created ....: 2025-07-01 12:00:00
Encryption key....: A5FA A005 5BED 4DC9 889D 38BC 30CB E8C4 B085 B9F7
created ....: 2025-07-01 12:00:00
Authentication key: 570E 1355 6D01 4C04 8B6D E2A3 AD9E 24E1 B8CB 9600
created ....: 2025-07-01 12:00:00
General key info..: sub rsa4096/0xB3CD10E502E19637 2025-07-01 YubiKey User <yubikey@example>
sec# rsa4096/0xF0F2CFEB04341FB5 created: 2025-07-01 expires: never
ssb> rsa4096/0xB3CD10E502E19637 created: 2025-07-01 expires: 2027-07-01
card-no: 0006 05553211
ssb> rsa4096/0x30CBE8C4B085B9F7 created: 2025-07-01 expires: 2027-07-01
card-no: 0006 05553211
ssb> rsa4096/0xAD9E24E1B8CB9600 created: 2025-07-01 expires: 2027-07-01
card-no: 0006 05553211sec# indicates the corresponding key is not available (the Certify key is offline).
YubiKey is now ready for use!
Encrypt a message to yourself (useful for storing credentials or protecting backups):
echo -e "\ntest message string" | \
gpg --encrypt --armor \
--recipient $KEYID --output encrypted.txtDecrypt the message - a prompt for the User PIN will appear:
gpg --decrypt --armor encrypted.txtTo encrypt to multiple recipients/keys, set the preferred key ID last:
echo "test message string" | \
gpg --encrypt --armor \
--recipient $KEYID_2 --recipient $KEYID_1 --recipient $KEYID \
--output encrypted.txtUse a shell function to make encrypting files easier:
secret () {
output="${1}".$(date +%s).enc
gpg --encrypt --armor --output ${output} \
-r $KEYID "${1}" && echo "${1} -> ${output}"
}
reveal () {
output=$(echo "${1}" | rev | cut -c16- | rev)
gpg --decrypt --output ${output} "${1}" && \
echo "${1} -> ${output}"
}Example output:
$ secret document.pdf
document.pdf -> document.pdf.1580000000.enc
$ reveal document.pdf.1580000000.enc
gpg: anonymous recipient; trying secret key 0xF0F2CFEB04341FB5 ...
gpg: okay, we are the anonymous recipient.
gpg: encrypted with RSA key, ID 0x0000000000000000
document.pdf.1580000000.enc -> document.pdfdrduh/Purse is a password manager based on GnuPG and YubiKey to securely store and use credentials.