Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

encrypt and decrypt text

by pearlie (Sexton)
on Feb 08, 2005 at 05:23 UTC ( #428928=perlquestion: print w/ replies, xml ) Need Help??
pearlie has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, i want to encrypt some text, store it for later use and then decrypt it when required. please suggest what i can use to do this that returns an encoded string instead of a whole block of lines(as does convert::uu).

Replies are listed 'Best First'.
Re: encrypt and decrypt text
by davido (Archbishop) on Feb 08, 2005 at 05:42 UTC

    What level of security is needed? For strong security there is Crypt::GPG. For weak obfuscation from casually prying eyes, there's ROT13, which could be written easily as "$string =~ tr/A-Za-z/N-ZA-Mn-za-m/;". Applied once, you rot-13 the standard English alphabet so that it can't be casually read. Applied a second time, and you undo the previous rotation.

    What is your ultimate objective, bullet proof security, mild obfuscation, ASCII encoding of binary data, or what?


Re: encrypt and decrypt text
by jbrugger (Parson) on Feb 08, 2005 at 05:51 UTC
    You also could have a look at Data::Serializer, it provides a unified interface to the various serializing modules currently available. Adds the functionality of both compression and encryption.
    example from cpan:
    use Data::Serializer; $obj = Data::Serializer->new(); $obj = Data::Serializer->new( serializer => 'Storable', digester => 'MD5', cipher => 'DES', secret => 'my secret', compress => 1, ); $serialized = $obj->serialize({a => [1,2,3],b => 5}); $deserialized = $obj->deserialize($serialized); print "$deserialized->{b}\n";

    Drawback may be 'spaces' to store sometimes go wrong. This can be solved by putting them in an array first, and store the array using Data::Serializer.
      I want simple encryption techniques. Can someone explain ROT-13 technique in a little more detail?

        There's not much to explain. The English alphabet consists of 26 letters (A through Z). You just rotate the alphabet 13 places, and now you've got N through Z followed by A through N. The most common way to do that in Perl is to use the tr/// operator to rotate the alphabet through the magic of transliteration. Try this:

        my $string = "Cleartext."; print $string, "\n"; $string = rot13( $string ); print $string, "\n"; $string = rot13( $string ); print $string, "\n"; sub rot13 { my $text = shift; $text = tr/A-Za-z/N-ZA-Mn-za-m/; return $text; }

        Not exactly strong encryption. Most decent newsreaders will be able to rot-13 text. Its original use on the Net was to prevent children and employers from accidentally seeing a curse word in some Usenet post. But the concept has been around since 3rd grade 200 years ago when Cracker Jacks first started putting decoder rings in their popcorn boxes. ;)


        Or, to be a little more "comprehensive" (and slightly less conventional, though still not seriously hard to "decrypt"), you could try "rot-23" -- here it is expressed with hex character codes (because hex is just easier for me, somehow):
        perl -pe 'tr{\x20-\x7d}{\x4f-\x7d\x20-\x4e}' clear.txt > cipher.txt
        And of course, doing the same thing on "cipher.txt" will turn it back into the original "clear.txt". This affects not just the alphabet letters, but all "printable" ascii characters from space through close-curly-brace (it leaves tildes alone, because you need to involve an even number of characters, and mutating spaces does a lot to help obscure the cleartext -- though it won't take someone long to figure out which "coded" character represents a space).
        I've had a bit more than a passing thought about placing this under the "Snippets" or "Code" areas, but have shyed away so far. I had a similar need just last week, and took some Rot-13 and other similar code to roll my own into the following:

        >less -x4

        #!/usr/bin/perl ###################################################################### +###### # This utility can modify a "string file" as defined below to obfuscat +e # those strings using a modified rot-13 type algorithm. String inform +ation # is to be supplied via filenames, or piped from a file/process into t +his # script. All output is to stdout, suitable for piping into a resulta +nt # file. # # The string file is to contain passwords or snmp community strings # ### # # Credits: Ideas taken from # # Thanks to TZapper and Tachyon's posts # # # # Thanks to Tanktalus #
        So, for example, you could have a file test.dat like so:
        > cat test.dat <p> public public private private our-read 0uR3ad our-write 0wR1t3 their-read th31read their-write theirwrong blah-blah blah-bl@h foo-bar barfoobar
        Then run the script against it, with a rotation of 13:
        > 13 test.dat > t.1 > cat t.1 # Rotational distance was undefined, assuming 0 13 public }$oyvp private }!v%n#r our-read =$_@nq our-write =&_>#@ their-read #u@>!rnq their-write #urv!&!|{t blah-blah oynu:oyMu foo-bar on!s||on!
        Using this code in actual expect or snmp scripts should be trival, though I've not gotten to that part in my own stuff yet :-)

        -Scott L. Miller

Re: encrypt and decrypt text
by perlsen (Chaplain) on Feb 08, 2005 at 05:59 UTC

    The Crypt::GPG module provides near complete access to GnuPG functionality through an object oriented interface. It provides methods for encryption, decryption, signing, signature verification, key generation, key export and import, and most other key management functions.

    This module works almost identically to its cousin, Crypt::PGP5. The two modules together provide a uniform interface to deal with both PGP and GnuPG. Eventually, these modules will be folded into a single module which will interface with GnuPG as well as all versions of PGP.

    I have seen this in cpan modules so that i extracted and given to your view

Re: encrypt and decrypt text
by zentara (Archbishop) on Feb 08, 2005 at 12:25 UTC
    Maybe simple RC4 is what you are after?
    #!/usr/bin/perl use strict; use warnings; use Crypt::RC4; use MIME::Base64; my $key = "abcdefghijklm"; my $plaintext = "Hello, World!"; my $encrypted = RC4($key, $plaintext); my $encoded = encode_base64($encrypted); my $decoded = decode_base64($encoded); print "$encoded\n"; print "$decoded\n"; my $decrypted = RC4($key, $decoded); print "$decrypted\n";

    I'm not really a human, but I play one on earth. flash japh
Re: encrypt and decrypt text
by holli (Monsignor) on Feb 08, 2005 at 11:03 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://428928]
Approved by davido
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2016-08-28 14:56 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (393 votes). Check out past polls.