logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

pbkdf2.ex (1453B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Password.Pbkdf2 do
  5. @moduledoc """
  6. This module implements Pbkdf2 passwords in terms of Plug.Crypto.
  7. """
  8. alias Plug.Crypto.KeyGenerator
  9. def decode64(str) do
  10. str
  11. |> String.replace(".", "+")
  12. |> Base.decode64!(padding: false)
  13. end
  14. def encode64(bin) do
  15. bin
  16. |> Base.encode64(padding: false)
  17. |> String.replace("+", ".")
  18. end
  19. def verify_pass(password, hash) do
  20. ["pbkdf2-" <> digest, iterations, salt, hash] = String.split(hash, "$", trim: true)
  21. salt = decode64(salt)
  22. iterations = String.to_integer(iterations)
  23. digest = String.to_existing_atom(digest)
  24. binary_hash =
  25. KeyGenerator.generate(password, salt, digest: digest, iterations: iterations, length: 64)
  26. encode64(binary_hash) == hash
  27. end
  28. def hash_pwd_salt(password, opts \\ []) do
  29. salt =
  30. Keyword.get_lazy(opts, :salt, fn ->
  31. :crypto.strong_rand_bytes(16)
  32. end)
  33. digest = Keyword.get(opts, :digest, :sha512)
  34. iterations =
  35. Keyword.get(opts, :iterations, Pleroma.Config.get([:password, :iterations], 160_000))
  36. binary_hash =
  37. KeyGenerator.generate(password, salt, digest: digest, iterations: iterations, length: 64)
  38. "$pbkdf2-#{digest}$#{iterations}$#{encode64(salt)}$#{encode64(binary_hash)}"
  39. end
  40. end