All pastes #738501 Raw Edit

gammy

public text v1 · immutable
·published 2007-10-16 11:34 UTC
rendered paste body
#!/usr/bin/perl -w
use strict;

my $keys = 3;
my $random_max = 5;
my @cipher;
push(@cipher, int(rand($random_max))) for(1..$keys);

print "Created " . @cipher . " keys\n";

my $original_message = "Hello, how are you?";

my $message_length = length($original_message) - 1;

# Create encrypted version
my $encrypted_message;
my $decrypted_message;
my $key = 0;
for(0..$message_length){
    # Get ASCII value of current character
    my $original_value = ord(substr($original_message, $_, 1));

    # Get our letter cipher key
    # We use modulus to rotate it around the number of keys we have.
    my $key = $cipher[$_ % @cipher];

    # Create the encrypted value by adding the cipher key to
    # the original value
    my $encrypted_value = $original_value + $key;

    # Translate the value back to a character
    my $encrypted_character = chr($encrypted_value);

    # Append the encrypted character to our string
    $encrypted_message .= $encrypted_character;
}

print "Original  : $original_message\n";
print "Encrypted : $encrypted_message\n";

# Translate it back.
# This code does _exactly_ the same as the
# encrypting code, but it subtracts instead of
# adds.
#
$key = 0;
$original_message = "";
for(0..$message_length){
    # Get ASCII value of current character
    my $encrypted_value = ord(substr($encrypted_message, $_, 1));

    # Get our letter cipher key
    # We use modulus to rotate it around the number of keys we have.
    my $key = $cipher[$_ % @cipher];

    # Create the decrypted value by subtracting the cipher key from
    # the encrypted value
    my $decrypted_value = $encrypted_value - $key;

    # Translate the value back to a character
    my $decrypted_character = chr($decrypted_value);

    # Append the encrypted character to our string
    $decrypted_message .= $decrypted_character;
}

print "Encrypted : $encrypted_message\n";
print "Descrypted: $decrypted_message\n";