CBC::CRYPT

[email protected] (Erik Sjöberg) Thu, 10 Oct 2002 05:29:05 +0200
Newsgroups perl.crypto
Message-ID <[email protected]>
Hi !

I have a problem with the implementation of the CBC/DES-encryption in my
programs.
I have a server and a client. The idea is that the client shall send an
encrypted message containing an XML-document. The server then recieves the
xml-document and runs the xml-parser on it after decryption.
Sometimes ("when i get lucky") the encryption and decryption works and
sometimes it does not.
I run these programs on win2k with activstate...
Do you know where I can find examples of cbc/des-implementations on the
Internet?
I am a beginner with perl and I would appreciate it very much i you could
give me som help with this...

/Erik


#!/usr/bin/perl -w

use IO::Socket;
use Crypt::CBC;

my $key = $ARGV[0];

$sock = new IO::Socket::INET (PeerAddr => 'localhost',
                              PeerPort => 1200,
                              Proto    => 'tcp',
                             );
die "Socket could not be created. Reason: $!\n" unless $sock;

$cipher = new Crypt::CBC($key,'DES');

my $msg = "<?xml version='1.0' encoding='iso-8859-1' ?><!DOCTYPE INFO SYSTEM
'protocol.dtd'><INFO><HOST IP='194.47.145.1'
MAC='00-10-5A-39-37-51'></HOST><HOST IP='194.47.145.2'
MAC='00-10-5A-39-37-52'></HOST><HOST IP='194.47.145.3'
MAC='00-10-5A-39-37-53'></HOST></INFO>";

$ciphertext = $cipher->encrypt($msg);
print $sock $ciphertext;
close ($sock);

----------------------------------------------


#!/usr/bin/perl -w

use IO::Socket;
use Crypt::CBC;
use XML::DOM;

my $sock;
my $new_sock;
my $message;
my $key = $ARGV[0];

$sock = new IO::Socket::INET (LocalHost => 'localhost',
                              LocalPort => 1200,
                              Proto     => 'tcp',
                              Listen    => 5,
                               Reuse     => 1
                             );
die "Socket could not be created. Reason: $!" unless $sock;

$cipher = new Crypt::CBC($key,'DES');

while ($new_sock = $sock->accept())
{
    while (defined ($message = <$new_sock>))
    {
	print "$message \n\n";
	$plaintext = $cipher->decrypt($message);
        print "$plaintext \n\n";

        my $parser = new XML::DOM::Parser;
	my $doc = $parser->parse ($plaintext);

 	my $hosts = $doc->getElementsByTagName ("HOST");
 	my $n = $hosts->getLength;

 	for (my $i = 0; $i < $n; $i++)
 	{
     		my $host = $hosts->item ($i);
     		my $ip = $host->getAttributeNode ("IP");
     		print $ip->getValue . "\n\n";
 	}

 	print $doc->toString . "\n\n";

	$doc->dispose;
    }
}
close ($sock);