Skip to content

Commit 9cd2f3b

Browse files
committed
Extract secret from otpauth uri
1 parent 5ec3d7d commit 9cd2f3b

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

lib/nimble_totp.ex

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,23 @@ defmodule NimbleTOTP do
157157
"otpauth://totp/#{URI.encode(label)}?#{query}"
158158
end
159159

160+
@doc """
161+
Extract the secret from an otpauth URI.
162+
163+
## Examples
164+
165+
iex> NimbleTOTP.secret_from_uri("otpauth://totp/Acme:alice?secret=MFRGGZA&issuer=Acme")
166+
{:ok, "abcd"}
167+
168+
"""
169+
@spec secret_from_uri(String.t()) :: {:ok, <<>>} | {:error, any()}
170+
def secret_from_uri(uri) when is_binary(uri) do
171+
with {:ok, uri} <- URI.new(uri),
172+
query = URI.decode_query(uri.query, %{}, :rfc3986),
173+
{:ok, secret} <- Map.fetch(query, "secret"),
174+
do: Base.decode32(secret, padding: false)
175+
end
176+
160177
@doc """
161178
Generate a binary composed of random bytes.
162179

0 commit comments

Comments
 (0)