| 1 | package OpenID::Lite::DH; | ||
| 2 | |||
| 3 | 1 | ▶ | use Any::Moose; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use Math::BigInt; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 0 | ▶ | use Crypt::DH::GMP; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 6 | use MIME::Base64; | ||
| 7 | use Carp (); | ||
| 8 | |||
| 9 | has 'p' => ( | ||
| 10 | is => 'ro', | ||
| 11 | isa => 'Str', | ||
| 12 | default => "155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443" | ||
| 13 | ); | ||
| 14 | |||
| 15 | has 'g' => ( | ||
| 16 | is => 'ro', | ||
| 17 | isa => 'Str', | ||
| 18 | default => "2", | ||
| 19 | ); | ||
| 20 | |||
| 21 | has 'dh' => ( | ||
| 22 | is => 'ro', | ||
| 23 | lazy_build => 1, | ||
| 24 | ); | ||
| 25 | |||
| 26 | sub _build_dh { | ||
| 27 | my $self = shift; | ||
| 28 | my $dh = Crypt::DH::GMP->new; | ||
| 29 | $dh->p($self->p); | ||
| 30 | $dh->g($self->g); | ||
| 31 | $dh->generate_keys(); | ||
| 32 | return $dh; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub generate_keys { | ||
| 36 | my $self = shift; | ||
| 37 | $self->dh->generate_keys(); | ||
| 38 | } | ||
| 39 | |||
| 40 | sub generate_public { | ||
| 41 | my $self = shift; | ||
| 42 | my $dh = $self->dh(); | ||
| 43 | my $pub = MIME::Base64::encode_base64(pack("B*", $dh->pub_key_twoc())); | ||
| 44 | $pub =~ s/\s+//g; | ||
| 45 | return $pub; | ||
| 46 | } | ||
| 47 | |||
| 48 | sub compute_public { | ||
| 49 | my ( $self, $public ) = @_; | ||
| 50 | my $dh = $self->dh(); | ||
| 51 | return pack('B*', $dh->compute_key_twoc($self->arg2bi($public))); | ||
| 52 | } | ||
| 53 | |||
| 54 | sub arg2bi { | ||
| 55 | my ( $self, $arg ) = @_; | ||
| 56 | return undef unless defined $arg and $arg ne ""; | ||
| 57 | return Math::BigInt->new("0") if length($arg) > 700; | ||
| 58 | return $self->bytes2bi(MIME::Base64::decode_base64($arg)); | ||
| 59 | } | ||
| 60 | |||
| 61 | sub bi2bytes { | ||
| 62 | my ( $self, $bigint ) = @_; | ||
| 63 | die if $bigint->is_negative; | ||
| 64 | my $bits = $bigint->as_bin; | ||
| 65 | die unless $bits =~ s/^0b//; | ||
| 66 | my $prepend = (8 - length($bits) % 8) || ($bits =~ /^1/ ? 8 : 0); | ||
| 67 | $bits = ("0" x $prepend) . $bits if $prepend; | ||
| 68 | return pack("B*", $bits); | ||
| 69 | } | ||
| 70 | |||
| 71 | sub bytes2bi { | ||
| 72 | my ( $self, $bytes ) = @_; | ||
| 73 | return Math::BigInt->new("0b" . unpack("B*", $bytes)); | ||
| 74 | } | ||
| 75 | |||
| 76 | no Any::Moose; | ||
| 77 | __PACKAGE__->meta->make_immutable; | ||
| 78 | 1; | ||
| 79 | |||
| 80 | |||