From ffb51a345234bdec730d786cfcf4326bc6c3352c Mon Sep 17 00:00:00 2001 From: Pavel Tsiukhtsiayeu Date: Thu, 30 Jan 2025 14:28:45 -0500 Subject: [PATCH] Refactored MPI encoding. Added exception for too long big-endian numbers --- lib/open_pgp/util.ex | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/lib/open_pgp/util.ex b/lib/open_pgp/util.ex index 8d37ddf..eb5c9a4 100644 --- a/lib/open_pgp/util.ex +++ b/lib/open_pgp/util.ex @@ -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 <>, 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) - - <> + @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 <>, do: bit + bit_count = bit_list |> Enum.drop_while(&(&1 == 0)) |> length() + + <> end @doc """