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