# I'm positive there's a better way to do this, but it works for a quick # example. require "bigint.pl"; # X^A mod Y, X^B mod Y # A is Alice's secret, B is Bob's secret # N1 is sent from Alice to Bob, N2 is sent from Bob to Alice # X and Y can be transferred in cleartext if necessary # Resulting K1 and K2 are the same, can be used as a crypto key # $X=123; $Y=711; ($A,$B) = (103,107); $N1 = DH($X,$A,$Y); $N2 = DH($X,$B,$Y); $K1 = DH($N2,$A,$Y); $K2 = DH($N1,$B,$Y); print "$X^$A % $Y = $N1\n"; print "$X^$B % $Y = $N2\n"; print "\n"; print "$N2^$A % $Y = $K1\n"; print "$N1^$B % $Y = $K2\n"; sub DH { my($X,$A,$Y) = @_; my $R = $X; for ( my $i = $A; $i > 1; $i-- ) { $R = bmul($R,$X); } return bmod($R,$Y); }