Current section
Files
Jump to
Current section
Files
lib/polyjuice/util/ed25519.ex
# Copyright 2019 Hubert Chathi <hubert@uhoreg.ca>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule Polyjuice.Util.Ed25519.SigningKey do
@opaque t :: %__MODULE__{
key: binary(),
id: String.t()
}
@enforce_keys [:key, :id]
defstruct [
:key,
:id
]
@doc """
Create a signing key from the base64 representation.
"""
@spec from_base64(key :: String.t(), id :: String.t()) :: __MODULE__.t()
def from_base64(<<key::binary-size(43)>>, id) when is_binary(id) do
{:ok, raw_key} = Base.decode64(key, padding: false, ignore: :whitespace)
%__MODULE__{key: raw_key, id: id}
end
defimpl Polyjuice.Util.SigningKey do
def sign(%{key: key}, msg) when is_binary(msg) do
:crypto.sign(:eddsa, :none, msg, [key, :ed25519]) |> Base.encode64(padding: false)
end
def id(%{id: id}), do: "ed25519:" <> id
def version(%{id: id}), do: id
def algorithm(_), do: "ed25519"
end
end
defmodule Polyjuice.Util.Ed25519.VerifyKey do
@opaque t :: %__MODULE__{
key: binary(),
id: String.t()
}
@enforce_keys [:key, :id]
defstruct [
:key,
:id
]
@doc """
Create a verify key from the base64 representation.
"""
@spec from_base64(key :: String.t(), id :: String.t()) :: __MODULE__.t()
def from_base64(<<key::binary-size(43)>>, id) when is_binary(id) do
{:ok, raw_key} = Base.decode64(key, padding: false, ignore: :whitespace)
%__MODULE__{key: raw_key, id: id}
end
defimpl Polyjuice.Util.VerifyKey do
def verify(%{key: key}, msg, sig) when is_binary(msg) and is_binary(sig) do
try do
{:ok, raw_sig} = Base.decode64(sig, padding: false)
:crypto.verify(:eddsa, :none, msg, raw_sig, [key, :ed25519])
rescue
_ -> false
end
end
def id(%{id: id}), do: "ed25519:" <> id
def version(%{id: id}), do: id
def algorithm(_), do: "ed25519"
end
end