1

Hello I am writing oauth 2 library to access google api's and my code is as follows

    jwt_create() ->

    {ok,PemBin} = file:read_file("your-key-file.pem"),
    PemEntry = public_key:pem_decode(PemBin),
    [A,B] = PemEntry,
    io:format("A:: ~p ~n",[A]),
    PrivateKey = public_key:pem_entry_decode(PemEntry),
    JwtHeaderJson = encode_json(jwt_header()),
    JwtClaimsetJson = encode_json(jwt_claimset()),
    ComputeSignature = compute_signature(JwtHeaderJson, JwtClaimsetJson, PrivateKey),
    Z=binary:replace(
      binary:replace(<<JwtHeaderJson/binary, ".", JwtClaimsetJson/binary, ".", ComputeSignature/binary>>,
                     <<"+">>, <<"-">>, [global]),
      <<"/">>, <<"_">>, [global]),
    io:format("JWT:: ~p ~n",[Z]).
compute_signature(Header, ClaimSet,#'RSAPrivateKey'{publicExponent=Exponent

                                                          ,modulus=Modulus

                                                          ,privateExponent=PrivateExponent}) ->
    base64:encode(crypto:sign(rsa, sha256, <<Header/binary, ".", ClaimSet/binary>>, 
            [Exponent, Modulus, PrivateExponent])).
encode_json(JWToken) ->
    base64:encode(jsx:encode(JWToken)).

I am getting error as follows:

exception error: no function clause matching public_key:pem_entry_decode([{'PrivateKeyInfo',<<48,130,4,191,2,1,0,48,13,6,9,42,134, 72,134,247,13,1,1,1,5,0,4,130,4,...>>, not_encrypted}, {'Certificate',<<48,130,3,96,48,130,2,72,160,3,2,1,2,2,8, 79,59,244,35,60,15,3,155,48,...>>, not_encrypted}]) (public_key.erl, line 123) in function googleoauth:jwt_create/0 (src/googleoauth.erl, line 55)

Please help me in generating JWS and JWT for OAUTH 2 for accessing google apis

Mofty
  • 416
  • 2
  • 9
  • 25
Krishna
  • 41
  • 4

1 Answers1

1

You are passing the wrong thing to public_key:pem_entry_decode/1:

This will resolve your problem:

PrivateKey = public_key:pem_entry_decode(A),

public_key:pem_entry_decode/1 takes a single pem_entry() but a PEM file can contain many entries, perhaps your code PemEntry = public_key:pem_decode(PemBin) should read PemEntries = public_key:pem_decode(PemBin) instead?

Also note the line before assumes 2 list entries, you might have meant this instead (not sure your intent here though)?

[A|B] = PemEntry,
Michael
  • 3,639
  • 14
  • 29