The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Crypt::PGP2 - module for programmatic PGP 2.x on Unix


Perl module wrapper for Unix PGP 2.x

You can get PGP from

This module:

  • is a wrapper that does parameter validation and provides application isolation from the external pgp program

  • returns the PGP banner and error constants.


The parameters are positional:

   $plaintext   Plaintext that you want to encrypt.

   $key         keyring id of recipient who has a public key.

   $options     PGP options you want, limited to any combination of 'a', and 't'.
                # -a means ASCII armour, needed when emailing ciphertext
                # -t means portable text newlines, needed for portability
                (Optional - default is -feat)


 encrypt returns a list of 3 scalars like this: ($ciphertext, $message, $error)

 $ciphertext    Ciphertext result of encrypting $Plaintext.

 $message       pgp statement and pgp banner returned from external program

 $error         error status from this program

 PGP_ERR_SUCCESS       - success
 PGP_ERR_FAIL          - failure to start external command
 PGP_ERR_BAD_OPTIONS   - optional pgp options invalid
 PGP_ERR_MISSING_KEY   - mandatory keyring ID missing
 PGP_ERR_MISSING_TEXT  - mandatory plaintext missing


 #!/usr/bin/perl -Tw

 $ENV{'PATH'} = '';

 use strict;      # must scope all symbols
 use diagnostics; # lint checking and verbose warnings

 use Crypt::PGP2;

 my $plaintext = 'Sample plaintext';
 my ($ciphertext, $msg, $error) = encrypt($plaintext,'james','at');

 if ($error == PGP_ERR_SUCCESS) {
    print "Ciphertext: $ciphertext\nMsg: $msg\nError: $error\n";
 else {
    print "PGP error: $error\n";


 PGP creates temporary work files, but we don't have
 control over this. This may be a security and reliability problem
 that you should investigate.

 Note that to encrypt a message, the only key required is the
 public key of the recipient. No private keys are required,
 so not even your private keyring needs to be on the same
 machine as the webserver. Only when signing a message or
 deciphering a message is a private key or keyring required.

 Your minimum key length should be 1024 bits and should be changed 


See Notes for general concerns. This module relies on Open3, which may not be supported on Windows NT. Only recent versions of Open3 do not leak memory.