How to use gpg --gen-key in a script?
Solution 1:
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