Crypt-MagicSignatures-Key

 view release on metacpan or  search on metacpan

lib/Crypt/MagicSignatures/Key.pm  view on Meta::CPAN

    return;
  };

  # Delete whitespace and padding
  $encoded_message =~ tr{=\t-\x0d }{}d;

  # Invalid message
  unless ($encoded_message) {
    carp 'No signature given';
    return;
  };

  # No modulus
  # return unless $self->n;

  # Verify message
  _verify_emsa_pkcs1_v1_5(
    $self,
    $message,
    # _b64url_to_hex( $encoded_message )
    b64url_decode($encoded_message)
  );
};



# Return MagicKey-String (public only)
sub to_string {
  my $self = shift;

  # return '' unless $n; # Shouldn't be possible

  # Convert modulus and exponent and add to component array
  my @array = ('RSA', _hex_to_b64url($self->n), _hex_to_b64url($self->e));

  if ($_[0] && $self->d) {
    push(@array, _hex_to_b64url($self->d));
  };

  # Specification is not clear about $mkey =~ s/=+//g;
  join('.', @array);
};


# Returns the b64 urlsafe encoding of a string
sub b64url_encode {
  return '' unless $_[0];

  my $v = $_[0];

  utf8::encode $v if utf8::is_utf8 $v;
  $v = encode_base64($v, '');
  $v =~ tr{+/\t-\x0d }{-_}d;

  # Trim padding or not
  $v =~ s/\=+$// unless (defined $_[1] ? $_[1] : 1);
  $v;
};


# Returns the b64 urlsafe decoded string
sub b64url_decode {
  my $v = shift;
  return '' unless $v;

  $v =~ tr{-_}{+/};

  my $padding;

  # Add padding
  if ($padding = (length($v) % 4)) {
    $v .= chr(61) x (4 - $padding);
  };

  decode_base64($v);
};


# Get octet length of n
sub _emLen {
  # return 0 unless $_[0]->n;
  ($_[0]->[4] // ($_[0]->[4] = _octet_len( $_[0]->n )));
};


# Sign with emsa padding
sub _sign_emsa_pkcs1_v1_5 {
  # http://www.ietf.org/rfc/rfc3447.txt [Ch. 8.1.1]

  # key, message
  my ($K, $M) = @_;

  # octet length of n
  my $k = $K->_emLen;

  # encode message (Hash digest is always 'sha-256')
  my $EM = _emsa_encode($M, $k) or return;

  _i2osp(_rsasp1($K, _os2ip($EM)), $k);
};


# Verify with emsa padding
sub _verify_emsa_pkcs1_v1_5 {
  # http://www.ietf.org/rfc/rfc3447.txt [Ch. 8.2.2]

  # key, message, signature
  my ($K, $M, $S) = @_;

  my $k = $K->_emLen;

  # The length of the signature is not
  # equivalent to the length of the RSA modulus
  # TODO: This probably needs to check octetlength
  if (length($S) != $k) {
    carp 'Invalid signature';
    return;
  };

  my $s = _os2ip($S);
  my $m = _rsavp1($K, $s) or return;



( run in 1.291 second using v1.01-cache-2.11-cpan-13bb782fe5a )