Dual-license your content for inclusion in The Perl 5 Wiki using this HOWTO, or join us for a chat on irc.freenode.net#PerlNet.

User:Raphael

From PerlNet

(Redirected from User:Belfry)
Jump to: navigation, search

Hey - thanks for stopping on by!

Time to start to move these things to their own pages, methinks.


Contents

Bio

Just a smidge about me - I'm a software developer and use Perl at work mainly for both web development and automating administrative tasks.

Currently I make good use of the Perl modules: CGI, Class::DBI, HTML::Mason, MIME::Lite, Email::Valid and CGI::Untaint amongst others. Soon I'll be using Catalyst for my web applications and also am keen to move into the Perl6 realm.

The below needs some work, but it's my notes (or more accurately notes from others and myself) on various Perl topics I'm interested in or need to know.

If you edit any of my pages, please sign and date it in order to give credit where due.


Thanks

Just a few thanks

  • Paul for helping me get started here, as well as everything else he's done
  • Jacinta for being generally helpful on heaps of topics, as well as everything else she does
  • all the Perl Mongers out there for being such a friendly and helpful mob
    • especially Sydney.PM (I'm the one standing on the far left in the photo of the wiki page)
  • Andrew Savige for being such a friendly, helpful and talented guy who has personally helped me


Disclaimer

I don't consider myself a "truely naturally talented Perl hacker", just someone who is trying to work hard on their craft to get "there". :)

Don't trust anything I say as the "truth" check it out for yourself. I may be wrong! (Let me know in a friendly manner though please!) :)


PDF Creation

From Jacinta

From: 	Jacinta Richardson
To: 	Raphael
Subject: 	RE: [Sydney-pm] PDF creation module
Date: 	Fri, 06 Jan 2006 15:09:17 +1100

G'day Raphael,

This kind of question seems to be asked a lot, so I've been keeping a file of answers. Not all of these will be useful to you, but I hope you'll find something in here of value.  :)

Jacinta


pdfs - Extremely simple strategy involves creating a HTML 3.2 document and then running html2ps and ps2pdf over it.

Java's iText through Inline::Java

PDF::API2 PDF::Create (avoid the CPAN-version (0.01) because it is very buggy - instead download from sourceforge) PDF::Reuse http://search.cpan.org/~mfrankl/HTML-HTMLDoc-0.09

http://sourceforge.net/projects/pdfcreator/

ps2pdf

CutePDF Writer

Creating PDF from scratch?

  • AxKit - www.axkit.org (xml.apache.org) , www.cpan.org/authors/id/M/MS/MSERGEANT/
  • pros
    • Perl based XML application server
    • XML ->XSLT -> PDF (or any other format)
    • active newsgroup, written/maintained by perl xml guru matt sergeant
  • cons
    • tricky to setup for newbies (tight integration b/w apache, mod_perl and perl )
    • may not be suitable for low volume usage

Converting formatted data to PDF?

  • pro
    • easier to convert originals rather than create from scratch
    • time to completion known
  • con
    • flexibility


Manipulating PDF?

  • read "Thinking in Postscript"
    • book's out of print. If you want to program it using perl tools then you have

to be aware of it's limitations

  • pro
    • flexible
  • con
    • time to completion
    • low code reuse

WARNING Most PDF files are not editable, most of the information you want to edit is gone forever by the time it makes it to PDF.

From Renee

To: 	Raphael Kraus 
CC:    Sydney Perl Mongers
Subject: 	Re: [Sydney-pm] PDF creation module
Date: 	Fri,  6 Jan 2006 06:28:20 +0100 (CET)  (16:28 EST)

G'day,

I use for simple tasks PDF::Create. But not the CPAN-version (0.01), but the Sourceforge.net-version (0.06). It has some limitations, but for texts, jpgs and so on, it is a very simple solution.

For bigger things, you could use PDF::API2 which is very good and powerful....

Regards, ReneeB --Belfry 21:45, 10 January 2006 (EST)

Thanks

Thanks to the following people for their input


Encrypting Sensitive Information

OK, as the web developer of several online forms I find myself having to manually encrypt sensitive information as it is collected to be stored in a database.

I'm looking at assymetric encryption (or public key encryption) meaning that different keys are used to encrypt and decrypt information. A public key, which anyone can see, is used to encrypt the information, whilst a private (secret) key is used to decrypt it.

One encryption algorithm well suited to this is RSA (the name is composed of the initials of the authors' surnames). Other algorithms are also involved, such as "Blowfish", but the workings of these we do not need to concern ourselves with at the moment.

FWIW, the general concensus seems to be that keys generated should be of size 2048 for credit card details encryption.

It is also good to know that the private key itself can be encrypted using a symetric encryption method (usually ...), being encrypted with a "pass phrase" rather than a password (i.e. like a password, only you can use some whitespace as well hence "phrase").


Warning

If you are doing cross-platform or cross-language encryption then you may run into non-trivial problems. (Todo: Fix-up below)

According to Stennie you may run into problems these problems due to different encryption libraries being used as well as different endian-ness (big vs little, platform dependent). Here is an email that Stephen sent to the Sydney.PM mailing list in response to some of my encryption queries.

From: Stennie
To: Sydney PM
Subject: [Sydney-pm] Two way encryption

> Can anyone recommend a module for encryption? (There are lots in  
> CPAN.)
>
> The encryption needs to be two-way. E.g. store encrypted data in  
> database,
> retrieve it and decrypt as needed.

Hi Raphael,

Are you doing cross-platform or cross-language encryption?  If not, then
you're pretty set using something like Crypt::CBC and Blowfish, or
Crypt::RSA.  I've found the most hasslesome module to install is
Math::Pari (a prereq for many of the crypto libs).. iirc, Blowfish
doesn't use this and may be easier to install.

If you are doing cross- something, I'd be wary .. some apparently
"standard" algorithms like Blowfish may not work easily (or at all!)
depending on the players involved (crypto implementations, endian-ness,
padding).

I had particular grief trying to convince Perl to exchange some crypted
info with Java (bouncycastle crypto lib).  Seemed to be some
unresolvable byte ordering bogusity in the initialisation vectors used,
similar to:
  http://groups.google.com/group/sci.crypt/browse_thread/thread/5c9cfbf91001a250/42f12f9e0a80c6bf?lnk=st

After many anguished experiments, the simplest workable solution we
found was to use openssl libs (e.g Crypt::OpenSSL::RSA, but first using
cmdline openssl to check the crypto might actually work).

I'm sure if we were dealing with same language / same architecture this
would not have been so grievous .. but hope that tip saves someone else
from stumbling through some very frustrating experiments ;).

Cheers,
Stephen

Included here with author's permission

Note on Endianess

It should be noted here that endianess shouldn't be a problem with the Blowfish/IDEA methods - but clearly they currently are and this is something that needs to be addresses.

A starting point for this argument comes from the Linux CIPE author, see: http://mail.nl.linux.org/linux-crypto/2001-02/msg00004.html

CPAN modules

There are heaps of modules in CPAN when you search on terms like "encryption", even searches like "public key encryption" return more results than what we'd like (or specific to the subject). Searching on RSA still gives us a heap of a results. Here are a few that I discovered, and the choices I've made.


OpenSSL::RSA

http://search.cpan.org/~oesi/OpenSSL-0.09/OpenSSL/RSA.pm

Whilst this module is advertised as "Access to OpenSSL RSA functions", it offers only a single function called new_keygen - I'm pretty sure I'm safe in assuming that this generates a RSA private key in the same manner that the *nix command `openssl genrsa` does.

It doesn't appear that this module appears to do what we'd like or even generate full keypairs, so unless I find some dire need I'll leave it alone.


Crypt::OpenSSL::RSA

http://search.cpan.org/~iroberts/Crypt-OpenSSL-RSA-0.22/RSA.pm

Now this module seems to be promising, and is based on the OpenSSL libraries.

Crypt::OpenSSL::RSA

  • Generates public and private RSA keys
  • Encrypts and decrypts plaintext to/from cyphertext using these keys


However

  • Generating keys longer than 512 bits results in a small memory leak
  • The user is responsible for retrieval and storage of keys from/to disk
  • No pass phrase can be used to encrypt/decrypt the private key
    (at least not from what I can see in the documentation)
  • Not all the links in the "See Also" section of the documentation seem to work from the the above link :(


Crypt::RSA

http://search.cpan.org/~vipul/Crypt-RSA-1.57/lib/Crypt/RSA.pm

A pure Perl implementation of the RSA cryptosystem.

Output appears like:

-----BEGIN COMPRESSED RSA ENCRYPTED MESSAGE-----
Version: 1.24
Scheme: Crypt::RSA::ES::OAEP

eJwBEQHu/jEwADI1NgBDeXBoZXJ0ZXh0eeFALKEDw6BtzHpFkfrvcSVSWsZilAl3skDslb2J/ff4
+u9aPtjjrVLz0FBavdTZa7G17BEM3N4m8TSqza6THr3E4Uub171J/OifsW89hUNe08ke2H/pvRbB
tM7dELRnMpktaVydjpL8/CymjnWgmy+o8OyVblLIlUZ99uOO5GsO+TtBsDCmMGqBmBIWfJD1Kw+S
gXH7bZ0XNudPDe4HWBBx5faFw0Nwc99cI0T1bZFqQyQInyTyw3oZsp8t13aggJBmjOPwmkM84H40
6WAVfQdF3ap4dBAySmuUdInsb0h3M1xTyvJ/nzlWUE4Sbix1Tj1GRuxgArREwq9oe6KL5hnLirg=
=dmprKMNI6XRyOKfi2bJ62Q==
-----END COMPRESSED RSA ENCRYPTED MESSAGE-----


Crypt::RSA

  • Generates public and private RSA keys
  • A pass phrase may be used to store the private key in an encrypted form
    (labelled password which is somewhat of a misnomer IMHO)
  • Filenames can be supplied for the storage and retrieval of keys to and from disk
  • Output appears in the neat self-documented form above


However

  • Serialisation and disk storage is in a form generated from Data::Dumper, rather than in the form that OpenSSL would store them in
    • I.e. this may cause a extra layer of complexity when trying to interoperate with other RSA cryptography software
  • Output appears in the neat self-documented form above, rather than just the encrypted string.


All in all, this would appear to be a nice little module, fairly well suited to our needs. It is my pick of modules.

We can extract just the encrypted string really easily, and even store the version and scheme separately if we see fit. With a bit more effort we may be able to overload the serialising and disk storage functionality to display and store the keys in Base64/DER encoding as per OpenSSL X509 certificates (I believe).


Example Code using Crypt::RSA

I wrote this code. Feel free to offer suggestions re best practices. There are no guarantees or promises regarding this example code. If your PC blows up or pets die - it's simply not my fault!


gen-keys.pl
#!/usr/bin/perl

use strict;
use warnings;

use Crypt::RSA;

print "Enter password: ";
my $passphrase = <>;
# WARNING: Passphrase echoed to terminal
# use Term::ReadKey module to turn off local echo if needed

my $rsa = new Crypt::RSA;
my ($public, $private) =
    $rsa->keygen(
        Size => 2048,
        Filename => 'key',
        Password => $passphrase,
    );
# Supplying the Filename paramater as such means that
# the public key will be written to key.public
# the private key will be written to key.private

print "Public key:\n"
    . $public->serialize
    . "\n\n"
    ;
print "Private key:\n"
    . $private->serialize
    . "\n\n"
    ;


encrypt.pl
#!/usr/bin/perl

use strict;
use warnings;
use Crypt::RSA;
use Crypt::RSA::Key::Public;

my $public = Crypt::RSA::Key::Public->new( Filename => 'key.public' );

my $rsa = Crypt::RSA->new();

my $message;
my $cypher;

print "Enter your message to encrypt: ";
$message = <>;

$cypher =
    $rsa->encrypt(
        Message => $message,
        Key => $public,
        Armour => 1,
    )
    or die "Unable to encrypt message - ".$rsa->errstr();

open OUT, "> message.cypher"
    or die "Unable to open message.cypher for writing! - $!";

print OUT $cypher;

close OUT;

print "Your encrypted message looks like:\n$cypher\n";


decrypt.pl
#!/usr/bin/perl

use strict;
use warnings;

use Term::ReadKey;
use Crypt::RSA;
use Crypt::RSA::Key::Private;

print "Enter pass phrase: ";
ReadMode 'noecho';
my $passphrase = ReadLine 0;
ReadMode 'restore';
print "\n";

my $private =
    Crypt::RSA::Key::Private->new(
        Filename => 'key.private',
        Password => $passphrase,
    );

open INPUT, "< message.cypher"
    or die "Unable to open message.cypher! - $!";

my $cypher = join(qq{}, <INPUT>);

close INPUT;

print "The cyphertext is:\n$cypher\n\n";

my $rsa = Crypt::RSA->new();

my $message =
    $rsa->decrypt(
        Cyphertext => $cypher,
        Key => $private,
        Armour => 1,
    )
    or die "Unable to decrypt cypher! - ".$rsa->errstr();

print "The message reads:\n$message\n";

Raphael 11:45, 20 January 2006 (EST)


Plans

Create

  • Crypt::RSA::Key::Private::X509 (or maybe call it Crypt::RSA::Key::Private::Base64) to manage Base64/DER encoded X509 private key certificates
  • Crypt::RSA::Key::Public::X509 (or maybe call it Crypt::RSA::Key::Public::Base64) to manage Base64/DER encoded X509 public key certificates
  • Crypt::RSA::whatever as a child of Crypt::RSA to add functions to provide methods to extract
    • just the encrypted cyphertext (i.e. without the nice header and footer)
    • the scheme
    • the version

First off I think I need to check that these things aren't already included in the modules and just aren't listed in the documentation.


Questions still remaining

  • How do you calculate storage requirements for encrypted text?
    • E.g. for storage in a database


Thanks

Thanks to the following people for their input

Personal tools