Convert::PEM(3pm)

🌸 NAME 🌸

Convert::PEM(3pm) is the manual page for Convert::PEM β€” and its whole thing is Read/write encrypted ASN.1 PEM files. That's the name, that's the game. πŸ’…


✨ SYNOPSIS ✨

Okay bestie, here's the vibe in code form:

           use Convert::PEM;
           my $pem = Convert::PEM->new(
                          Name => "DSA PRIVATE KEY",
                          Macro => "DSAPrivateKey",
                          ASN => qq(
                              DSAPrivateKey SEQUENCE {
                                  version INTEGER,
                                  p INTEGER,
                                  q INTEGER,
                                  g INTEGER,
                                  pub_key INTEGER,
                                  priv_key INTEGER
                              }
                         ));

           my $keyfile = 'private-key.pem';
           my $pwd = 'foobar';

           my $pkey = $pem->read(
                          Filename => $keyfile,
                          Password => $pwd
                    );

           $pem->write(
                          Content  => $pkey,
                          Password => $pwd,
                          Filename => $keyfile
                    );

πŸ’« DESCRIPTION πŸ’«

Convert::PEM reads and writes PEM files containing ASN.1-encoded objects. The files can optionally be encrypted using a symmetric cipher algorithm, such as 3DES. An unencrypted PEM file might look something like this:

           -----BEGIN DH PARAMETERS-----
           MB4CGQDUoLoCULb9LsYm5+/WN992xxbiLQlEuIsCAQM=
           -----END DH PARAMETERS-----

The string beginning "MB4C..." is the Base64-encoded, ASN.1-encoded "object."

An encrypted file would have headers describing the type of encryption used, and the initialization vector:

           -----BEGIN DH PARAMETERS-----
           Proc-Type: 4,ENCRYPTED
           DEK-Info: DES-EDE3-CBC,C814158661DC1449

           AFAZFbnQNrGjZJ/ZemdVSoZa3HWujxZuvBHzHNoesxeyqqidFvnydA==
           -----END DH PARAMETERS-----

The two headers ("Proc-Type" and "DEK-Info") indicate information about the type of encryption used, and the string starting with "AFAZ..." is the Base64-encoded, encrypted, ASN.1-encoded contents of this "object."

The initialization vector ("C814158661DC1449") is chosen randomly.


πŸ¦‹ USAGE πŸ¦‹

$pem = Convert::PEM->new( %arg )

Constructs a new Convert::PEM object designed to read/write an object of a specific type (given in %arg, see below). Returns the new object on success, undef on failure (see ERROR HANDLING for details).

%arg can contain:

  • Name β€” the name of the object; when decoding a PEM-encoded stream, the name in the encoding will be checked against the value of Name. Similarly, when encoding an object, the value of Name will be used as the name of the object in the PEM-encoded content. For example, given the string "FOO BAR", the output from encode will start with a header like:
             -----BEGIN FOO BAR-----

Name is a required argument.

  • ASN β€” an ASN.1 description of the content to be either encoded or decoded.

ASN is an optional argument.

  • Macro β€” if your ASN.1 description (in the ASN parameter) includes more than one ASN.1 macro definition, you will want to use the Macro parameter to specify which definition to use when encoding/decoding objects. For example, if your ASN.1 description looks like this:
             Foo ::= SEQUENCE {
                 x INTEGER,
                 bar Bar
             }

             Bar ::= INTEGER

If you want to encode/decode a "Foo" object, you will need to tell Convert::PEM to use the "Foo" macro definition by using the Macro parameter and setting the value to "Foo".

Macro is an optional argument when an ASN.1 description is provided.

  • InForm β€” specify what type of file to expect when using the read method. Value may be either PEM or DER. Default is "PEM".

If "DER" is specified, encryption options are ignored when using the read method and file is read as an unencrypted blob. This option does not affect the decode behavior.

InForm is an optional argument.

  • OutForm β€” specify what type of file the write method should output. Value may be either PEM or DER. Default is "PEM".

If "DER" is specified, encryption options are ignored when using the write method and the file is written as an uncrypted blob. This option does not affect the encode behavior.

OutForm is an optional argument.

$obj = $pem->decode(%args)

Decodes, and, optionally, decrypts a PEM file, returning the object as decoded by Convert::ASN1. The difference between this method and read is that read reads the contents of a PEM file on disk; this method expects you to pass the PEM contents as an argument.

If an error occurs while reading the file or decrypting/decoding the contents, the function returns undef, and you should check the error message using the errstr method (below).

%args can contain:

  • Content β€” the PEM contents.
  • Password β€” the password with which the file contents were encrypted.

If the file is encrypted, this is a mandatory argument (well, it's not strictly mandatory, but decryption isn't going to work without it). Otherwise it's not necessary.

$blob = $pem->encode(%args)

Constructs the contents for the PEM file from an object: ASN.1-encodes the object, optionally encrypts those contents.

Returns undef on failure (encryption failure, file-writing failure, etc.); in this case you should check the error message using the errstr method (below). On success returns the constructed PEM string.

%args can contain:

  • Content β€” this method requires either Content or DER. An error will be generated if one of these arguments are not present.

A hash reference that will be passed to Convert::ASN1::encode, and which should correspond to the ASN.1 description you gave to the new method. The hash reference should have the exact same format as that returned from the read method.

This is required unless DER is specified.

  • DER β€” a string containing actual binary of the contents to be encoded. This bypasses ASN.1 encoding.

May be used in lieu of Content. If specified, will override Content.

  • Password β€” a password used to encrypt the contents of the PEM file. This is an optional argument; if not provided the contents will be unencrypted.
  • Cipher β€” the Cipher to use if a password is provided. This is an optional argument; if not provided, the default of DES-EDE3-CBC will be used or the cipher configured is $Convert::PEM::DefaultCipher. See below for a list of supported ciphers.

$obj = $pem->read(%args)

Reads, decodes, and, optionally, decrypts a PEM file, returning the object as decoded by Convert::ASN1 (or binary blob if ASN.1 description was not provided). This is implemented as a wrapper around decode, with the bonus of reading the PEM file from disk for you.

If an error occurs while reading the file or decrypting/decoding the contents, the function returns undef, and you should check the error message using the errstr method (below).

In addition to the arguments that can be passed to the decode method (minus the Content argument), %args can contain:

  • Filename β€” the location of the PEM file that you wish to read.
  • InForm β€” specify what file type to read. Description can be found under new method. If specified, will override InForm provided in new method.

$pem->write(%args)

Constructs the contents for the PEM file from an object: ASN.1-encodes the object, optionally encrypts those contents; then writes the file to disk. This is implemented as a wrapper around encode, with the bonus of writing the file to disk for you.

Returns undef on failure (encryption failure, file-writing failure, etc.); in this case you should check the error message using the errstr method (below). On success returns the constructed PEM string.

In addition to the arguments for encode, %args can contain:

  • Filename β€” the location on disk where you'd like the PEM file written.
  • OutForm β€” specify format to write out. Description can be found under new method. If specified, will override OutForm provided in new method.

$pem->from_der(%args)

Method used internally, but may be accessed directly decode an ASN.1 string into a perl structure object. If the Convert::PEM object has no ASN.1 definition, this method has no effect.

  • DER β€” binary string to convert to an object.

This option is required.

  • Macro β€” if the object has an ASN definition, a Macro may be specified. If specified, it will override the object's Macro if one exists.

Macro is an optional argument.

$pem->to_der(%args)

Method used internally, but may be accessed directly to encode Content into binary data. If the Convert::PEM object has no ASN.1 definition, this method has no effect.

  • Content β€” an object to be ASN.1 encoded to a binary string.
  • Macro β€” if the object has an ASN definition, a Macro may be specified. If specified, it will override the object's Macro if one exists.

Macro is an optional argument.

$pem->errstr

Returns the value of the last error that occurred. This should only be considered meaningful when you've received undef from one of the functions above; in all other cases its relevance is undefined.

$pem->asn

Returns the Convert::ASN1 object used internally to decode and encode ASN.1 representations. This is useful when you wish to interact directly with that object; for example, if you need to call configure on that object to set the type of big-integer class to be used when decoding/encoding big integers:

           $pem->asn->configure( decode => { bigint => 'Math::Pari' },
                                 encode => { bigint => 'Math::Pari' } );

$pem->inform

Retruns the InForm configured for the object.

$pem->outform

Retruns the OutForm configured for the object.

$pem->cipher

Returns the Cipher configured for the object.

$pem->name

Returns the PEM Name of the object.


βš™οΈ CONFIGURATION βš™οΈ

Okay bestie, listen up β€” if you want any encryption/decryption to actually work, you need to have the right cipher module installed. No module, no vibes. That's just how it is. πŸ’…

Some of the settings can be peeked at or tweaked through variables or methods.

Heads up: these config settings are global to the whole package. Change one and it affects every single Convert::PEM object out there. Every. Single. One. πŸ‘€

πŸ’– $Convert::PEM::DefaultCipher or $OBJ->DefaultCipher([NEW_CIPHER])

This one sets up a default cipher for when you're writing stuff to disk. When you use the method form $OBJ->DefaultCipher([NEW_CIPHER]) and you don't pass a NEW_CIPHER, it'll just hand you back whatever the current setting is. And if the cipher you pass is not recognized/valid? Boom, an error gets raised. 😭

Wanna see all the supported ciphers? Hit up Convert::PEM::list_ciphers. Here's the full roster:

  • DES-CBC
  • DES-EDE3-CBC
  • AES-128-CBC
  • AES-192-CBC
  • AES-256-CBC
  • CAMELLIA-128-CBC
  • CAMELLIA-192-CBC
  • CAMELLIA-256-CBC
  • IDEA-CBC
  • SEED-CBC

✨ so many options, we love a versatile queen ✨


πŸ” Convert::PEM->has_cipher($cipher_name)

Checks if the cipher is supported and has an encryption module configured. Simple vibe check, nothing more.


πŸ•΅οΈ Convert::PEM->has_cipher_module($cipher_name)

Checks if the cipher is supported and whether the configured encryption module is actually usable. If it's not usable, it returns undef. If it is usable, you get the name of the cipher module back. πŸŽ€


πŸ› οΈ Convert::PEM->set_cipher_module($cipher,$module[,$all])

This function/method is how you tell the package which module name goes with a supported cipher. It takes 2 or 3 arguments.

Convert::PEM->set_cipher_module(<cipher_name>, <module_name>[,0])
or
$OBJ->set_cipher_module(<cipher_name>, <module_name>[,0])

cipher_name

A supported cipher name. Use Convert::PEM::list_ciphers() to grab the list of supported ciphers.

module_name

A cipher module. And no, it can't just be any random module β€” it has to support these methods:

$cipher_object = Cipher->new($key)
$cipher_object->encrypt($plaintext)
$cipher_object->decrypt($ciphertext)
$cipher_object->blocksize()

all

An optional boolean argument. If it's true, it'll replace the modules for all supported ciphers that match the cipher you're setting. Default is true. And lowkey important: if you're setting a cipher, only set this to false if you specifically want a separate cipher for different key lengths of the same algorithm. iykyk 🫢


πŸ“‹ Convert::PEM->list_cipher_modules([$cipher_name])

If you pass a cipher_name, you get back the module configured for the matching cipher name β€” or undef if that cipher isn't supported. If you don't pass a cipher_name, you get a list of module names, returned as an array in array context or as a colon separated list in scalar context. Versatile! πŸ‘‘

Here's the list of cipher modules used by default:

  • Crypt::DES
  • Crypt::DES_EDE3
  • Crypt::Rijndael β€” "AES-128-CBC, AES-192-CBC and AES-256-CBC"
  • Crypt::Camellia β€” "CAMELLIA-128-CBC, CAMELLIA-192-CBC and CAMELLIA-256-CBC"
  • Crypt::IDEA
  • Crypt::SEED

πŸ’€ ERROR HANDLING πŸ’€

If an error happens in any of the methods above, the method returns undef. Then it's on you to call the method errstr to figure out where the error came from:

$pem->errstr

And if you don't even have a Convert::PEM object yet β€” like, say, an error occurred while creating a Convert::PEM object β€” you can still get that error as a class method:

Convert::PEM->errstr

For example, if you try to decode an encrypted object and you don't hand over a passphrase to decrypt it:

my $obj = $pem->read( Filename => "encrypted.pem" )
    or die "Decryption failed: ", $pem->errstr;

See how it gracefully catches the L and tells you why? That's the energy. 🌸


πŸ“œ LICENSE πŸ“œ

Convert::PEM is free software; you may redistribute it and/or modify it under the same terms as Perl itself. Slay, open source. πŸ¦‹


πŸ‘‘ AUTHOR & COPYRIGHTS πŸ‘‘

Except where otherwise noted, Convert::PEM is Copyright Benjamin Trott, cpan@stupidfool.org. All rights reserved.


That's the whole page bestie, we made it to the end πŸŽ‰ this one's from perl v5.40.0, dated 2024-12-03, and it's Convert::PEM(3pm). Go forth and encrypt responsibly πŸ’–βœ¨

πŸ“¦ where this page comes from