Search code examples
elixirphoenix-framework

How to use Plug.Crypto.decrypt?


I want to encrypt a string and the decrypt it, for encryption i did

enc_str = Plug.Crypto.encrypt("my_secret",  "raw_string", {})

And for decrypt y tried this two

Plug.Crypto.decrypt("my_secret", enc_str)
Plug.Crypto.decrypt("my_secret", enc_str, {})

which returns the following errors

** (FunctionClauseError) no function clause matching in Plug.Crypto.decrypt/2
** (FunctionClauseError) no function clause matching in Plug.Crypto.decrypt/5

How can enc_str be decrypted properly? I Only found 2 references to this methods, but i really dont understand them https://hexdocs.pm/plug_crypto/Plug.Crypto.html#decrypt/4 https://shyr.io/blog/elixir-encrypt-data-plug-crypto


Solution

  • The arguments to encrypt/4 are:

    1. The secret key base, usually taken from conn.secret_key_base (which if you are using Phoenix, is set based on your config)
    2. Your secret, which acts as salt to encrypt the data
    3. The data you want to encrypt - can be any term - no need to be "raw_string"
    4. Opts specified in the documentation

    Example, from inside a plug:

    encrypted =
      Plug.Crypto.encrypt(conn.secret_key_base, "mmm salty", %{hello: "world!"})
      |> IO.inspect(label: "encrypted")
    
    decrypted =
      Plug.Crypto.decrypt(conn.secret_key_base, "mmm salty", encrypted)
      |> IO.inspect(label: "decrypted")
    

    Output:

    encrypted: "QTEyOEdDTQ.R83_rKqB0vyw2KJmGZmjhEuRqc-En71p--VGDaRhpzOEXHIxeg_TOE4YCvQ.bsuQLhrrKzE0LOFo.qooCxTQrJQ7S8lTRhngprcEgAODvw_IsIgGofAEC1_F3NyIcaocQVns.KqKtO6hVMPk0dxOXjX-67A"
    decrypted: {:ok, %{hello: "world!"}}
    

    Or since you are using Phoenix, you can use Phoenix.Token.encrypt/4 with a conn:

    Phoenix.Token.encrypt(conn, "mmm salty", %{hello: "world!"})
    

    Or an endpoint:

    Phoenix.Token.encrypt(YourAppWeb.Endpoint, "mmm salty", %{hello: "world!"})