Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Encrypt String Crypt::CBC

by docbrown25 (Initiate)
on Jan 23, 2013 at 15:04 UTC ( #1014924=perlquestion: print w/replies, xml ) Need Help??

docbrown25 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I'm trying to encrypt a string then base64 encode it so its safe for use in a url.

Is there anyway to encrypt a string using Crypt::CBC so that each run would produce a completely different output? I get close with the following but the first 11 chars (im guessing its the random header) are always the same in my output, even though the rest of the encytped string changes.

my $key = 'somerandomkey'; my $cipher = Crypt::CBC->new( -key => $key, -header => 'randomiv', -cypher => 'Blowfish', ); my $ciphertext = $cipher->encrypt($string); my $safe_data = urlsafe_b64encode($ciphertext);

I'v also tried -header=> none with an iv and that produces the exact same result for each run.

Any help is appreciated. thanks.

Replies are listed 'Best First'.
Re: Encrypt String Crypt::CBC
by gryphon (Abbot) on Jan 23, 2013 at 17:25 UTC

    Greetings docbrown25,

    From what I can tell from my very limited playing with Crypt::CBC is that to do what you want, you'll need to generate an initialization vector per each encryption, then prepend that IV to the head of the blob before encoding. You'll have to reverse that process of course when decoding and decrypting.

    Here's an example bit of code that randomly generates IVs, then uses these to encrypt/encode a URL. Then the decode/decrypt process pulls the IV off the head of the data.

    #!/usr/bin/perl use strict; use warnings; use Crypt::CBC; use MIME::Base64::URLSafe qw( urlsafe_b64encode urlsafe_b64decode ); my $key = 'secret'; sub url_encode { my ( $string, $iv ) = @_; return urlsafe_b64encode( $iv . Crypt::CBC->new( '-key' => $key, '-header' => 'none', '-iv' => $iv, '-cypher' => 'Blowfish', )->encrypt($string) ); } sub url_decode { my $b64 = urlsafe_b64decode( $_[0] ); return Crypt::CBC->new( '-key' => $key, '-header' => 'none', '-iv' => substr( $b64, 0, 8 ), '-cypher' => 'Blowfish', )->decrypt( substr( $b64, 8 ) ); } foreach ( 1 .. 5 ) { my $iv = join( '', map { [ 'a' .. 'z' ]->[ rand(26) ] } ( 1 .. 8 ) + ); my $en_string = url_encode( '', $iv ); my $de_string = url_decode($en_string); print $iv, ' : ', $en_string, ' => ', $de_string, "\n"; }

    Hope this helps.

      this is great. exactly what I was looking for. thank you very much!

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2020-11-29 13:15 GMT
Find Nodes?
    Voting Booth?

    No recent polls found