%% Generated by the Erlang ASN.1 BER compiler. Version: 5.5
%% Purpose: Encoding and decoding of the types in ECPrivateKey.

-module('ECPrivateKey').
-moduledoc false.
-compile(nowarn_unused_vars).
-dialyzer(no_improper_lists).
-dialyzer(no_match).
-include("ECPrivateKey.hrl").
-asn1_info([{vsn,'5.5'},
            {module,'ECPrivateKey'},
            {options,[{i,"/buildroot/otp/lib/public_key/asn1/../src"},
 warnings,ber,errors,
 {cwd,"/buildroot/otp/lib/public_key/asn1"},
 {outdir,"/buildroot/otp/lib/public_key/asn1/../src"},
 der,noobj,asn1config,
 {i,"."},
 {i,"/buildroot/otp/lib/public_key/asn1"}]}]).

-export([encoding_rule/0,maps/0,bit_string_format/0,
         legacy_erlang_types/0]).
-export(['dialyzer-suppressions'/1]).
-export([
enc_ECPrivateKey/2
]).

-export([
dec_ECPrivateKey/2
]).

-export([info/0]).

-export([encode/2,decode/2]).

encoding_rule() -> ber.

maps() -> false.

bit_string_format() -> bitstring.

legacy_erlang_types() -> false.

encode(Type, Data) ->
try iolist_to_binary(element(1, encode_disp(Type, Data))) of
  Bytes ->
    {ok,Bytes}
  catch
    Class:Exception:Stk when Class =:= error; Class =:= exit ->
      case Exception of
        {error,{asn1,Reason}} ->
          {error,{asn1,{Reason,Stk}}};
        Reason ->
         {error,{asn1,{Reason,Stk}}}
      end
end.


decode(Type, Data) ->
try
   Result = decode_disp(Type, element(1, ber_decode_nif(Data))),
   {ok,Result}
  catch
    Class:Exception:Stk when Class =:= error; Class =:= exit ->
      case Exception of
        {error,{asn1,Reason}} ->
          {error,{asn1,{Reason,Stk}}};
        Reason ->
         {error,{asn1,{Reason,Stk}}}
      end
end.

encode_disp('ECPrivateKey', Data) -> enc_ECPrivateKey(Data);
encode_disp(Type, _Data) -> exit({error,{asn1,{undefined_type,Type}}}).

decode_disp('ECPrivateKey', Data) -> dec_ECPrivateKey(Data);
decode_disp(Type, _Data) -> exit({error,{asn1,{undefined_type,Type}}}).

info() ->
   case ?MODULE:module_info(attributes) of
     Attributes when is_list(Attributes) ->
       case lists:keyfind(asn1_info, 1, Attributes) of
         {_,Info} when is_list(Info) ->
           Info;
         _ ->
           []
       end;
     _ ->
       []
   end.


%%================================
%%  ECPrivateKey
%%================================
enc_ECPrivateKey(Val) ->
    enc_ECPrivateKey(Val, [<<48>>]).

enc_ECPrivateKey(Val, TagIn) ->
{_,Cindex1,Cindex2,Cindex3,Cindex4,Cindex5} = Val,

%%-------------------------------------------------
%% attribute version(1) with type INTEGER
%%-------------------------------------------------
   {EncBytes1,EncLen1} = encode_integer(Cindex1, [{ecPrivkeyVer1,1}], [<<2>>]),

%%-------------------------------------------------
%% attribute privateKey(2) with type OCTET STRING
%%-------------------------------------------------
   {EncBytes2,EncLen2} = encode_restricted_string(Cindex2, [<<4>>]),

%%-------------------------------------------------
%% attribute parameters(3) with type CHOICE OPTIONAL
%%-------------------------------------------------
   {EncBytes3,EncLen3} =  case Cindex3 of
         asn1_NOVALUE -> {<<>>,0};
         _ ->
            'enc_ECPrivateKey_parameters'(Cindex3, [<<160>>])
       end,

%%-------------------------------------------------
%% attribute publicKey(4) with type BIT STRING OPTIONAL
%%-------------------------------------------------
   {EncBytes4,EncLen4} =  case Cindex4 of
         asn1_NOVALUE -> {<<>>,0};
         _ ->
            encode_unnamed_bit_string(Cindex4, [<<3>>,<<161>>])
       end,

%%-------------------------------------------------
%% attribute attributes(5) with type ASN1_OPEN_TYPE OPTIONAL
%%-------------------------------------------------
   {EncBytes5,EncLen5} =  case Cindex5 of
         asn1_NOVALUE -> {<<>>,0};
         _ ->
            encode_open_type(Cindex5, [])
       end,

   BytesSoFar = [EncBytes1, EncBytes2, EncBytes3, EncBytes4, EncBytes5],
LenSoFar = EncLen1 + EncLen2 + EncLen3 + EncLen4 + EncLen5,
encode_tags(TagIn, BytesSoFar, LenSoFar).



%%================================
%%  ECPrivateKey_parameters
%%================================
enc_ECPrivateKey_parameters(Val, TagIn) ->
      {EncBytes,EncLen} = case element(1,Val) of
      namedCurve ->
         encode_object_identifier(element(2,Val), [<<6>>]);
      Else -> 
         exit({error,{asn1,{invalid_choice_type,Else}}})
   end,

encode_tags(TagIn, EncBytes, EncLen).




dec_ECPrivateKey(Tlv) ->
   dec_ECPrivateKey(Tlv, [16]).

dec_ECPrivateKey(Tlv, TagIn) ->
   %%-------------------------------------------------
   %% decode tag and length 
   %%-------------------------------------------------
Tlv1 = match_tags(Tlv, TagIn),

%%-------------------------------------------------
%% attribute version(1) with type INTEGER
%%-------------------------------------------------
[V1|Tlv2] = Tlv1, 
Term1 = begin
Val1 = decode_integer(V1, [2]),
if 1 =< Val1, Val1 =< 1 ->
Val2 = Val1,
number2name(Val2, [{ecPrivkeyVer1,1}]);
true ->
exit({error,{asn1,bad_range}})
end
end,

%%-------------------------------------------------
%% attribute privateKey(2) with type OCTET STRING
%%-------------------------------------------------
[V2|Tlv3] = Tlv2, 
Term2 = decode_octet_string(V2, [4]),

%%-------------------------------------------------
%% attribute parameters(3) with type CHOICE OPTIONAL
%%-------------------------------------------------
{Term3,Tlv4} = case Tlv3 of
[{131072,V3}|TempTlv4] ->
    {'dec_ECPrivateKey_parameters'(V3, []), TempTlv4};
    _ ->
        { asn1_NOVALUE, Tlv3}
end,

%%-------------------------------------------------
%% attribute publicKey(4) with type BIT STRING OPTIONAL
%%-------------------------------------------------
{Term4,Tlv5} = case Tlv4 of
[{131073,V4}|TempTlv5] ->
    {decode_native_bit_string(V4, [3]), TempTlv5};
    _ ->
        { asn1_NOVALUE, Tlv4}
end,

%%-------------------------------------------------
%% attribute attributes(5) with type ASN1_OPEN_TYPE OPTIONAL
%%-------------------------------------------------
{Term5,Tlv6} = case Tlv5 of
[V5|TempTlv6] ->
    {decode_open_type_as_binary(V5, []), TempTlv6};
    _ ->
        { asn1_NOVALUE, Tlv5}
end,

case Tlv6 of
[] -> true;_ -> exit({error,{asn1, {unexpected,Tlv6}}}) % extra fields not allowed
end,
Res1 = {'ECPrivateKey',Term1,Term2,Term3,Term4,Term5},
Res1.
'dec_ECPrivateKey_parameters'(Tlv, TagIn) ->
Tlv1 = match_tags(Tlv, TagIn),
case (case Tlv1 of [CtempTlv1] -> CtempTlv1; _ -> Tlv1 end) of

%% 'namedCurve'
    {6, V1} -> 
        {namedCurve, decode_object_identifier(V1, [])};

      Else -> 
         exit({error,{asn1,{invalid_choice_tag,Else}}})
   end
.

%%%
%%% Run-time functions.
%%%

'dialyzer-suppressions'(Arg) ->
    ok.

ber_decode_nif(B) ->
    asn1rt_nif:decode_ber_tlv(B).

ber_encode([Tlv]) ->
    ber_encode(Tlv);
ber_encode(Tlv) when is_binary(Tlv) ->
    Tlv;
ber_encode(Tlv) ->
    asn1rt_nif:encode_ber_tlv(Tlv).

collect_parts(TlvList) ->
    collect_parts(TlvList, []).

collect_parts([{_, L} | Rest], Acc) when is_list(L) ->
    collect_parts(Rest, [collect_parts(L) | Acc]);
collect_parts([{3, <<Unused,Bits/binary>>} | Rest], _Acc) ->
    collect_parts_bit(Rest, [Bits], Unused);
collect_parts([{_T, V} | Rest], Acc) ->
    collect_parts(Rest, [V | Acc]);
collect_parts([], Acc) ->
    list_to_binary(lists:reverse(Acc)).

collect_parts_bit([{3, <<Unused,Bits/binary>>} | Rest], Acc, Uacc) ->
    collect_parts_bit(Rest, [Bits | Acc], Unused + Uacc);
collect_parts_bit([], Acc, Uacc) ->
    list_to_binary([Uacc | lists:reverse(Acc)]).

dec_subidentifiers(<<>>, _Av, Al) ->
    lists:reverse(Al);
dec_subidentifiers(<<1:1,H:7,T/binary>>, Av, Al) ->
    dec_subidentifiers(T, Av bsl 7 + H, Al);
dec_subidentifiers(<<H,T/binary>>, Av, Al) ->
    dec_subidentifiers(T, 0, [Av bsl 7 + H | Al]).

decode_integer(Tlv, TagIn) ->
    Bin = match_tags(Tlv, TagIn),
    Len = byte_size(Bin),
    <<Int:Len/signed-unit:8>> = Bin,
    Int.

decode_native_bit_string(Buffer, Tags) ->
    case match_and_collect(Buffer, Tags) of
        <<0>> ->
            <<>>;
        <<Unused,Bits/binary>> ->
            Size = bit_size(Bits) - Unused,
            <<Val:Size/bitstring,_:Unused/bitstring>> = Bits,
            Val
    end.

decode_object_identifier(Tlv, Tags) ->
    Val = match_tags(Tlv, Tags),
    [AddedObjVal | ObjVals] = dec_subidentifiers(Val, 0, []),
    {Val1, Val2} =
        if
            AddedObjVal < 40 ->
                {0, AddedObjVal};
            AddedObjVal < 80 ->
                {1, AddedObjVal - 40};
            true ->
                {2, AddedObjVal - 80}
        end,
    list_to_tuple([Val1, Val2 | ObjVals]).

decode_octet_string(Tlv, TagsIn) ->
    Bin = match_and_collect(Tlv, TagsIn),
    binary:copy(Bin).

decode_open_type_as_binary(Tlv, TagIn) ->
    ber_encode(match_tags(Tlv, TagIn)).

e_object_identifier({'OBJECT IDENTIFIER', V}) ->
    e_object_identifier(V);
e_object_identifier(V) when is_tuple(V) ->
    e_object_identifier(tuple_to_list(V));
e_object_identifier([E1, E2 | Tail]) ->
    Head = 40 * E1 + E2,
    {H, Lh} = mk_object_val(Head),
    {R, Lr} = lists:mapfoldl(fun enc_obj_id_tail/2, 0, Tail),
    {[H | R], Lh + Lr}.

enc_obj_id_tail(H, Len) ->
    {B, L} = mk_object_val(H),
    {B, Len + L}.

encode_integer(Val) ->
    Bytes =
        if
            Val >= 0 ->
                encode_integer_pos(Val, []);
            true ->
                encode_integer_neg(Val, [])
        end,
    {Bytes, length(Bytes)}.

encode_integer(Val, NamedNumberList, Tag) when is_atom(Val) ->
    case lists:keyfind(Val, 1, NamedNumberList) of
        {_, NewVal} ->
            encode_tags(Tag, encode_integer(NewVal));
        _ ->
            exit({error, {asn1, {encode_integer_namednumber, Val}}})
    end;
encode_integer(Val, _NamedNumberList, Tag) ->
    encode_tags(Tag, encode_integer(Val)).

encode_integer_neg(-1, [B1 | _T] = L) when B1 > 127 ->
    L;
encode_integer_neg(N, Acc) ->
    encode_integer_neg(N bsr 8, [N band 255 | Acc]).

encode_integer_pos(0, [B | _Acc] = L) when B < 128 ->
    L;
encode_integer_pos(N, Acc) ->
    encode_integer_pos(N bsr 8, [N band 255 | Acc]).

encode_length(L) when L =< 127 ->
    {[L], 1};
encode_length(L) ->
    Oct = minimum_octets(L),
    Len = length(Oct),
    if
        Len =< 126 ->
            {[128 bor Len | Oct], Len + 1};
        true ->
            exit({error, {asn1, too_long_length_oct, Len}})
    end.

encode_object_identifier(Val, TagIn) ->
    encode_tags(TagIn, e_object_identifier(Val)).

encode_open_type(Val, T) when is_list(Val) ->
    encode_open_type(list_to_binary(Val), T);
encode_open_type(Val, Tag) ->
    encode_tags(Tag, Val, byte_size(Val)).

encode_restricted_string(OctetList, TagIn) when is_binary(OctetList) ->
    encode_tags(TagIn, OctetList, byte_size(OctetList));
encode_restricted_string(OctetList, TagIn) when is_list(OctetList) ->
    encode_tags(TagIn, OctetList, length(OctetList)).

encode_tags(TagIn, {BytesSoFar, LenSoFar}) ->
    encode_tags(TagIn, BytesSoFar, LenSoFar).

encode_tags([Tag | Trest], BytesSoFar, LenSoFar) ->
    {Bytes2, L2} = encode_length(LenSoFar),
    encode_tags(Trest,
                [Tag, Bytes2 | BytesSoFar],
                LenSoFar + byte_size(Tag) + L2);
encode_tags([], BytesSoFar, LenSoFar) ->
    {BytesSoFar, LenSoFar}.

encode_unnamed_bit_string(Bits, TagIn) ->
    Unused = (8 - bit_size(Bits) band 7) band 7,
    Bin = <<Unused,Bits/bitstring,0:Unused>>,
    encode_tags(TagIn, Bin, byte_size(Bin)).

match_and_collect(Tlv, TagsIn) ->
    Val = match_tags(Tlv, TagsIn),
    case Val of
        [_ | _] = PartList ->
            collect_parts(PartList);
        Bin when is_binary(Bin) ->
            Bin
    end.

match_tags({T, V}, [T]) ->
    V;
match_tags({T, V}, [T | Tt]) ->
    match_tags(V, Tt);
match_tags([{T, V}], [T | Tt]) ->
    match_tags(V, Tt);
match_tags([{T, _V} | _] = Vlist, [T]) ->
    Vlist;
match_tags(Tlv, []) ->
    Tlv;
match_tags({Tag, _V} = Tlv, [T | _Tt]) ->
    exit({error, {asn1, {wrong_tag, {{expected, T}, {got, Tag, Tlv}}}}}).

minimum_octets(0, Acc) ->
    Acc;
minimum_octets(Val, Acc) ->
    minimum_octets(Val bsr 8, [Val band 255 | Acc]).

minimum_octets(Val) ->
    minimum_octets(Val, []).

mk_object_val(0, Ack, Len) ->
    {Ack, Len};
mk_object_val(Val, Ack, Len) ->
    mk_object_val(Val bsr 7, [Val band 127 bor 128 | Ack], Len + 1).

mk_object_val(Val) when Val =< 127 ->
    {[255 band Val], 1};
mk_object_val(Val) ->
    mk_object_val(Val bsr 7, [Val band 127], 1).

number2name(Int, NamedNumberList) ->
    case lists:keyfind(Int, 2, NamedNumberList) of
        {NamedVal, _} ->
            NamedVal;
        _ ->
            Int
    end.
