How to use gpg --gen-key in a script?
OpenSSL does not support OpenPGP, so you can't use it for key generation. Anyway, GnuPG is rather easy to script using --with-colons
together with --batch
. For most operations, using GPGME is the way to go, at least for high-level programming languages where libraries exist to interface GnuPG through it without having to parse the output on your own.
Also scripted key generation is possible: you're looking for unattended key generation, which is well possible. In the end it boils down to storing a description on how to generate the keys in a file, and running gpg --batch --genkey [filename]
.
The documentation linked above hosts following example on unattended key generation:
$ cat >foo <<EOF
%echo Generating a basic OpenPGP key
Key-Type: DSA
Key-Length: 1024
Subkey-Type: ELG-E
Subkey-Length: 1024
Name-Real: Joe Tester
Name-Comment: with stupid passphrase
Name-Email: [email protected]
Expire-Date: 0
Passphrase: abc
%pubring foo.pub
%secring foo.sec
# Do a commit here, so that we can later print "done" :-)
%commit
%echo done
EOF
$ gpg2 --batch --gen-key foo
[...]
$ gpg2 --no-default-keyring --secret-keyring ./foo.sec \
--keyring ./foo.pub --list-secret-keys
/home/wk/work/gnupg-stable/scratch/foo.sec
------------------------------------------
sec 1024D/915A878D 2000-03-09 Joe Tester (with stupid passphrase) <[email protected]>
ssb 1024g/8F70E2C0 2000-03-09
Related videos on Youtube
teknopaul
Updated on September 18, 2022Comments
-
teknopaul over 1 year
GnuPG is one of these annoying tools that has a non-scriptable command line.
I want to run
gpg --gen-key
in a script, the rest of the process is simple commands. Any one had any luck with this? Entering the password seems to be supported, but not the other questions it asks, key type, key size, expiry, name.If you use the
--yes
option, it still shows confirmation dialogs.Is there any way some more friendly tool like
openssl
can be used to generate keys? -
Scott - Слава Україні over 8 yearsBTW, congratulations.
-
Ben Creasy over 6 yearsNote that as of 2.1,
%secring filename
is a no-op and an ephemeral directory is used instead: gnupg.org/documentation/manuals/gnupg/…