Skip to content

Commit

Permalink
Refactored MPI encoding. Added exception for too long big-endian numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
paveltyk committed Jan 30, 2025
1 parent 801225c commit ffb51a3
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions lib/open_pgp/util.ex
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,18 @@ defmodule OpenPGP.Util do
iex> OpenPGP.Util.encode_mpi(<<0x1, 0xFF>>)
<<0x0, 0x9, 0x1, 0xFF>>
iex> :crypto.strong_rand_bytes(65536) |> OpenPGP.Util.encode_mpi()
** (RuntimeError) big-endian is too long
"""
@spec encode_mpi(mpi_value :: binary()) :: binary()
def encode_mpi(mpi_value) do
bits = for <<bit::1 <- mpi_value>>, do: bit
bsize = bit_size(mpi_value)

mpi_length =
Enum.reduce_while(bits, bsize, fn
1, acc -> {:halt, acc}
0, acc -> {:cont, acc - 1}
end)

<<mpi_length::16, mpi_value::binary>>
@spec encode_mpi(big_endian :: binary()) :: mpi :: <<_::16, _::_*8>>
def encode_mpi("" <> _ = big_endian) do
if byte_size(big_endian) > 65535, do: raise("big-endian is too long")

bit_list = for <<bit::1 <- big_endian>>, do: bit
bit_count = bit_list |> Enum.drop_while(&(&1 == 0)) |> length()

<<bit_count::16, big_endian::binary>>
end

@doc """
Expand Down

0 comments on commit ffb51a3

Please sign in to comment.