Skip to content

Instantly share code, notes, and snippets.

@aliyousefiaan
Last active January 14, 2024 15:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliyousefiaan/36b62e6e5f28339942119baedbee7428 to your computer and use it in GitHub Desktop.
Save aliyousefiaan/36b62e6e5f28339942119baedbee7428 to your computer and use it in GitHub Desktop.
-module(compress_ecdsa_publickey).
-export([compress_ecdsa_publickey/1, test/0]).
compress_ecdsa_publickey(UncompressedPublicKey) ->
%% To binary
UncompressedPublicKeyBin = binary:decode_hex(list_to_binary(UncompressedPublicKey)),
%% Check that the uncompressed public key is valid
case size(UncompressedPublicKeyBin) of
65 ->
%% Remove the prefix (first byte) from the public key
PublicKey = binary:part(
UncompressedPublicKeyBin, 1, byte_size(UncompressedPublicKeyBin) - 1
),
%% Extract the x-coordinate
X = binary:part(PublicKey, 0, 32),
%% Extract the y-coordinate
Y = binary:part(PublicKey, 32, 32),
%% Extract the y-coordinate last byte
YLastByte = binary:last(Y),
%% Determine whether the y-coordinate is even or odd
case YLastByte rem 2 of
0 -> Prefix = <<2>>;
1 -> Prefix = <<3>>
end,
%% Concatenate prefix and x to obtain the compressed public key
CompressedPublicKey = <<Prefix/binary, X/binary>>,
{ok, binary_to_list(binary:encode_hex(CompressedPublicKey))};
_ ->
io:format("Invalid public key ~p, The public key has length of: ~p", [
UncompressedPublicKey, size(UncompressedPublicKeyBin)
]),
error
end.
test() ->
UncompressedPublicKey = "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
%% Call the compress_ecdsa_publickey function
compress_ecdsa_publickey(UncompressedPublicKey).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment