Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

did:key generation #5

Merged
merged 20 commits into from
Feb 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ hexpds-*.tar

# Temporary files, for example, from tests.
/tmp/
priv/native/libhexpds_k256.so
23 changes: 18 additions & 5 deletions lib/hexpds/didgenerator.ex
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
defmodule Hexpds.DidGenerator do
require Logger
alias :crypto, as: Crypto
alias ExSecp256k1, as: Secp256k1
alias Hexpds.K256, as: K256

def generate_private_key(), do: Crypto.strong_rand_bytes(32)

@spec get_public_key(binary()) :: binary() | {:error, String.t()}
def get_public_key(privkey) when is_binary(privkey) and byte_size(privkey) == 32 do
case(Secp256k1.create_public_key(privkey)) do
case(K256.create_public_key(privkey)) do
{:ok, pubkey} -> pubkey
_ -> {:error, "Invalid private key"}
_ -> raise "Error generating public key"
end
end

def create_did_web_pubkey(pubkey) do
# Convert public key to the required format and encode
@spec multicodec_encode(binary(), :"secp256k1-pub") :: <<_::16, _::_*8>>
def multicodec_encode(pubkey, :"secp256k1-pub") do
<<0xE7, 0x01, pubkey::binary>>
end

@spec create_public_did_key(binary()) :: String.t()
def create_public_did_key(pubkey) do
"did:key:" <>
(case pubkey |> K256.compress_public_key() do
{:ok, pubkey} -> pubkey
_ -> raise "Error compressing public key"
end
|> Base.decode16!(case: :lower)
|> multicodec_encode(:"secp256k1-pub")
|> Multibase.encode!(:base58_btc))
end

def sign_genesis(genesis, privkey) do
Expand Down
5 changes: 5 additions & 0 deletions lib/hexpds/k256.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
defmodule Hexpds.K256 do
use Rustler, otp_app: :hexpds, crate: "hexpds_k256"
def create_public_key(private_key), do: :erlang.nif_error(:nif_not_loaded)
def compress_public_key(public_key), do: :erlang.nif_error(:nif_not_loaded)
end
Empty file added lib/hexpds/mst.ex
Empty file.
3 changes: 2 additions & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ defmodule Hexpds.MixProject do
{:cbor, "~> 1.0.0"},
{:jason, "~> 1.4"},
{:ex_doc, "~> 0.28.0", only: :dev, runtime: false},
{:ex_secp256k1, "~> 0.7.2"},
{:multibase, "~> 0.0.1"},
{:ex_multihash, "~> 2.0.0"},
{:rustler, "~> 0.30.0"},
{:toml, "~> 0.7.0"}
]
end
end
13 changes: 13 additions & 0 deletions mix.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@
"base1": {:hex, :base1, "0.1.0", "493a46bb5b34bf38d3b69ea6eaff33416d222f1621231cb1a04af42a351117ea", [:mix], [], "hexpm", "57cb13fe05f3dc4174c7fbca147b94dcfdceea1ce87fdd5f803a29d3ca75fc96"},
"base2": {:hex, :base2, "0.1.0", "bc9e19f1578e1439010d26b1bee456f3ac980481a46c3643b24e15c40e1db0ed", [:mix], [], "hexpm", "a25eb2892e03f609fd5634aaf9a7795fb90f98dc9a7a495ed8c03b2844bbb647"},
"basefiftyeight": {:hex, :basefiftyeight, "0.1.0", "3d48544743bf9aab7ab02aed803ac42af77acf268c7d8c71d4f39e7fa85ee8d3", [:mix], [], "hexpm", "af12f551429528c711e98628c029ad48d1e5ba5a284f40b2d91029a65381837a"},
"bitcoinex": {:hex, :bitcoinex, "0.1.7", "2357049df10ba79e701138481692326863553476fd902c1c5a6e918d7f93b721", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:timex, "~> 3.1", [hex: :timex, repo: "hexpm", optional: false]}], "hexpm", "06f2d2c84b98ada2cf87106e54b7cc309497281f2bbf601e86b8528cfbd6e9fd"},
"castore": {:hex, :castore, "1.0.5", "9eeebb394cc9a0f3ae56b813459f990abb0a3dedee1be6b27fdb50301930502f", [:mix], [], "hexpm", "8d7c597c3e4a64c395980882d4bca3cebb8d74197c590dc272cfd3b6a6310578"},
"cbor": {:hex, :cbor, "1.0.1", "39511158e8ea5a57c1fcb9639aaa7efde67129678fee49ebbda780f6f24959b0", [:mix], [], "hexpm", "5431acbe7a7908f17f6a9cd43311002836a34a8ab01876918d8cfb709cd8b6a2"},
"certifi": {:hex, :certifi, "2.12.0", "2d1cca2ec95f59643862af91f001478c9863c2ac9cb6e2f89780bfd8de987329", [:rebar3], [], "hexpm", "ee68d85df22e554040cdb4be100f33873ac6051387baf6a8f6ce82272340ff1c"},
"combine": {:hex, :combine, "0.10.0", "eff8224eeb56498a2af13011d142c5e7997a80c8f5b97c499f84c841032e429f", [:mix], [], "hexpm", "1b1dbc1790073076580d0d1d64e42eae2366583e7aecd455d1215b0d16f2451b"},
"csv": {:hex, :csv, "2.5.0", "c47b5a5221bf2e56d6e8eb79e77884046d7fd516280dc7d9b674251e0ae46246", [:mix], [{:parallel_stream, "~> 1.0.4 or ~> 1.1.0", [hex: :parallel_stream, repo: "hexpm", optional: false]}], "hexpm", "e821f541487045c7591a1963eeb42afff0dfa99bdcdbeb3410795a2f59c77d34"},
"decimal": {:hex, :decimal, "2.1.1", "5611dca5d4b2c3dd497dec8f68751f1f1a54755e8ed2a966c2633cf885973ad6", [:mix], [], "hexpm", "53cfe5f497ed0e7771ae1a475575603d77425099ba5faef9394932b35020ffcc"},
"earmark_parser": {:hex, :earmark_parser, "1.4.39", "424642f8335b05bb9eb611aa1564c148a8ee35c9c8a8bba6e129d51a3e3c6769", [:mix], [], "hexpm", "06553a88d1f1846da9ef066b87b57c6f605552cfbe40d20bd8d59cc6bde41944"},
"ex_doc": {:hex, :ex_doc, "0.28.6", "2bbd7a143d3014fc26de9056793e97600ae8978af2ced82c2575f130b7c0d7d7", [:mix], [{:earmark_parser, "~> 1.4.19", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "bca1441614654710ba37a0e173079273d619f9160cbcc8cd04e6bd59f1ad0e29"},
"ex_multihash": {:hex, :ex_multihash, "2.0.0", "7fb36f842a2ec1c6bbba550f28fcd16d3c62981781b9466c9c1975c43d7db43c", [:mix], [], "hexpm", "66a08a86a1ba00d95736c595d7975696e5691308cdf7770c50b0f84a2a1172b0"},
"ex_secp256k1": {:hex, :ex_secp256k1, "0.7.2", "33398c172813b90fab9ab75c12b98d16cfab472c6dcbde832b13c45ce1c01947", [:mix], [{:rustler, ">= 0.0.0", [hex: :rustler, repo: "hexpm", optional: true]}, {:rustler_precompiled, "~> 0.6", [hex: :rustler_precompiled, repo: "hexpm", optional: false]}], "hexpm", "f3b1bf56e6992e28b9d86e3bf741a4aca3e641052eb47d13ae4f5f4d4944bdaf"},
"expo": {:hex, :expo, "0.5.1", "249e826a897cac48f591deba863b26c16682b43711dd15ee86b92f25eafd96d9", [:mix], [], "hexpm", "68a4233b0658a3d12ee00d27d37d856b1ba48607e7ce20fd376958d0ba6ce92b"},
"gettext": {:hex, :gettext, "0.24.0", "6f4d90ac5f3111673cbefc4ebee96fe5f37a114861ab8c7b7d5b30a1108ce6d8", [:mix], [{:expo, "~> 0.5.1", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "bdf75cdfcbe9e4622dd18e034b227d77dd17f0f133853a1c73b97b3d6c770e8b"},
"hackney": {:hex, :hackney, "1.20.1", "8d97aec62ddddd757d128bfd1df6c5861093419f8f7a4223823537bad5d064e2", [:rebar3], [{:certifi, "~> 2.12.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "~> 6.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "~> 1.0.0", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~> 1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:parse_trans, "3.4.1", [hex: :parse_trans, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "~> 1.1.0", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}, {:unicode_util_compat, "~> 0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "fe9094e5f1a2a2c0a7d10918fee36bfec0ec2a979994cff8cfe8058cd9af38e3"},
"httpoison": {:hex, :httpoison, "1.8.2", "9eb9c63ae289296a544842ef816a85d881d4a31f518a0fec089aaa744beae290", [:mix], [{:hackney, "~> 1.17", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm", "2bb350d26972e30c96e2ca74a1aaf8293d61d0742ff17f01e0279fef11599921"},
"idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~> 0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"},
Expand All @@ -20,10 +26,17 @@
"mimerl": {:hex, :mimerl, "1.2.0", "67e2d3f571088d5cfd3e550c383094b47159f3eee8ffa08e64106cdf5e981be3", [:rebar3], [], "hexpm", "f278585650aa581986264638ebf698f8bb19df297f66ad91b18910dfc6e19323"},
"monad": {:hex, :monad, "1.0.5", "bd02263a8dad0894433ca3283ebb6f71a55799e1cd17bda1e8b2ea9e14eeb9c5", [:mix], [], "hexpm", "d8ebe20971160e96bd6cdf11b5e8b5c24b70fddde3d198e5f7c3b5ebfbc78d6e"},
"multibase": {:hex, :multibase, "0.0.1", "9243bebe6f7f0f9f873c770ddcddab285cc554a8dd2374b8de6b2add087eccbc", [:mix], [{:base1, "~> 0.1.0", [hex: :base1, repo: "hexpm", optional: false]}, {:base2, "~> 0.1.0", [hex: :base2, repo: "hexpm", optional: false]}, {:basefiftyeight, "~> 0.1.0", [hex: :basefiftyeight, repo: "hexpm", optional: false]}, {:zbase32, "~> 2.0.0", [hex: :zbase32, repo: "hexpm", optional: false]}], "hexpm", "6ea13a19e47da727c2def81b241ad10a39440c5705a4abed18e8310b46f45f51"},
"multicodec": {:git, "https://github.com/ShreyanJain9/ex-multicodec.git", "7570cd559691e414a67223e9e8a7fd4ad2d7549b", [branch: "master"]},
"nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"},
"parallel_stream": {:hex, :parallel_stream, "1.1.0", "f52f73eb344bc22de335992377413138405796e0d0ad99d995d9977ac29f1ca9", [:mix], [], "hexpm", "684fd19191aedfaf387bbabbeb8ff3c752f0220c8112eb907d797f4592d6e871"},
"parse_trans": {:hex, :parse_trans, "3.4.1", "6e6aa8167cb44cc8f39441d05193be6e6f4e7c2946cb2759f015f8c56b76e5ff", [:rebar3], [], "hexpm", "620a406ce75dada827b82e453c19cf06776be266f5a67cff34e1ef2cbb60e49a"},
"rustler": {:hex, :rustler, "0.30.0", "cefc49922132b072853fa9b0ca4dc2ffcb452f68fb73b779042b02d545e097fb", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:toml, "~> 0.6", [hex: :toml, repo: "hexpm", optional: false]}], "hexpm", "9ef1abb6a7dda35c47cfc649e6a5a61663af6cf842a55814a554a84607dee389"},
"rustler_precompiled": {:hex, :rustler_precompiled, "0.7.1", "ecadf02cc59a0eccbaed6c1937303a5827fbcf60010c541595e6d3747d3d0f9f", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: false]}, {:rustler, "~> 0.23", [hex: :rustler, repo: "hexpm", optional: true]}], "hexpm", "b9e4657b99a1483ea31502e1d58c464bedebe9028808eda45c3a429af4550c66"},
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.7", "354c321cf377240c7b8716899e182ce4890c5938111a1296add3ec74cf1715df", [:make, :mix, :rebar3], [], "hexpm", "fe4c190e8f37401d30167c8c405eda19469f34577987c76dde613e838bbc67f8"},
"timex": {:hex, :timex, "3.7.11", "bb95cb4eb1d06e27346325de506bcc6c30f9c6dea40d1ebe390b262fad1862d1", [:mix], [{:combine, "~> 0.10", [hex: :combine, repo: "hexpm", optional: false]}, {:gettext, "~> 0.20", [hex: :gettext, repo: "hexpm", optional: false]}, {:tzdata, "~> 1.1", [hex: :tzdata, repo: "hexpm", optional: false]}], "hexpm", "8b9024f7efbabaf9bd7aa04f65cf8dcd7c9818ca5737677c7b76acbc6a94d1aa"},
"toml": {:hex, :toml, "0.7.0", "fbcd773caa937d0c7a02c301a1feea25612720ac3fa1ccb8bfd9d30d822911de", [:mix], [], "hexpm", "0690246a2478c1defd100b0c9b89b4ea280a22be9a7b313a8a058a2408a2fa70"},
"tzdata": {:hex, :tzdata, "1.1.1", "20c8043476dfda8504952d00adac41c6eda23912278add38edc140ae0c5bcc46", [:mix], [{:hackney, "~> 1.17", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm", "a69cec8352eafcd2e198dea28a34113b60fdc6cb57eb5ad65c10292a6ba89787"},
"unicode_util_compat": {:hex, :unicode_util_compat, "0.7.0", "bc84380c9ab48177092f43ac89e4dfa2c6d62b40b8bd132b1059ecc7232f9a78", [:rebar3], [], "hexpm", "25eee6d67df61960cf6a794239566599b09e17e668d3700247bc498638152521"},
"varint": {:hex, :varint, "1.4.0", "b7405c8a99db7b95d4341fa9cb15e7c3af6c8dda43e21bbe1c4a9cdff50b6502", [:mix], [], "hexpm", "0fd461901b7120c03467530dff3c58fa3475328fd75ba72c7d3cbf13bce6b0d2"},
"zbase32": {:hex, :zbase32, "2.0.0", "5a61d5ee8f39092d4a243da2a42b5b4339ef226d9b182603f63d5a3f16d192ee", [:mix], [], "hexpm", "798f81895658f9773e1dcf30ba3c118547f482502c5e1e19e72752f9a6f23e44"},
}
5 changes: 5 additions & 0 deletions native/hexpds_k256/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[target.'cfg(target_os = "macos")']
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]
14 changes: 14 additions & 0 deletions native/hexpds_k256/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Generated by Cargo
# will have compiled files and executables
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
17 changes: 17 additions & 0 deletions native/hexpds_k256/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "hexpds_k256"
version = "0.1.0"
authors = [ "NetWatchInc" ]
edition = "2021"

[lib]
name = "hexpds_k256"
path = "src/lib.rs"
crate-type = ["cdylib"]

[dependencies]
atoms = "2.2.3"
elliptic-curve = "0.13.8"
hex = "0.4.3"
k256 = "0.13.3"
rustler = "0.30.0"
20 changes: 20 additions & 0 deletions native/hexpds_k256/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# NIF for Elixir.Hexpds.k256

## To build the NIF module:

- Your NIF will now build along with your project.

## To load the NIF:

```elixir
defmodule Hexpds.K256 do
use Rustler, otp_app: :hexpds, crate: "hexpds_k256"

# When your NIF is loaded, it will override this function.
def create_public_key(private_key), do: :erlang.nif_error(:nif_not_loaded)
end
```

## Examples

[This](https://github.com/rusterlium/NifIo) is a complete example of a NIF written in Rust.
44 changes: 44 additions & 0 deletions native/hexpds_k256/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use rustler::{Binary, Encoder, Env, Term};
use k256::{elliptic_curve::sec1::ToEncodedPoint, PublicKey, SecretKey};
use hex;

mod atoms {
rustler::atoms! {
ok,
error,
}
}

#[rustler::nif]
fn create_public_key<'a>(env: Env<'a>, private_key: Binary<'a>) -> Term<'a> {

let secret_key = match SecretKey::from_slice(&private_key) {
Ok(key) => key,
Err(e) => return (atoms::error(), format!("Failed to create secret key: {}", e)).encode(env),
};

let public_key = secret_key.public_key();

let public_key_hex = hex::encode(public_key.to_encoded_point(false).as_bytes());

(atoms::ok(), public_key_hex).encode(env)
}

#[rustler::nif]
fn compress_public_key<'a>(env: Env<'a>, public_key: Binary<'a>) -> Term<'a> {
let public_key = match hex::decode(public_key.as_slice()) {
Ok(key) => key,
Err(e) => return (atoms::error(), format!("Failed to decode hex string: {}", e)).encode(env),
};

let public_key = match PublicKey::from_sec1_bytes(&public_key) {
Ok(key) => key,
Err(e) => return (atoms::error(), format!("Failed to parse public key: {}", e)).encode(env),
};

let compressed_key = hex::encode(public_key.to_encoded_point(true).as_bytes());
(atoms::ok(), compressed_key).encode(env)
}

rustler::init!("Elixir.Hexpds.K256", [create_public_key, compress_public_key]);

Binary file added priv/native/libhexpds_k256.so
Binary file not shown.
28 changes: 28 additions & 0 deletions test/hexpds_didgenerator_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule HexpdsDidGeneratorTest do
use ExUnit.Case
doctest Hexpds.DidGenerator

defp test_cases do
%{
"9085d2bef69286a6cbb51623c8fa258629945cd55ca705cc4e66700396894e0c" =>
"did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme",
"f0f4df55a2b3ff13051ea814a8f24ad00f2e469af73c363ac7e9fb999a9072ed" =>
"did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2",
"6b0b91287ae3348f8c2f2552d766f30e3604867e34adc37ccbb74a8e6b893e02" =>
"did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N",
"c0a6a7c560d37d7ba81ecee9543721ff48fea3e0fb827d42c1868226540fac15" =>
"did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy",
"175a232d440be1e0788f25488a73d9416c04b6f924bea6354bf05dd2f1a75133" =>
"did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj"
}
end

test "derives correct did:key" do
for {privkey_hex, expected_did} <- test_cases() do
assert privkey_hex
|> Base.decode16!(case: :lower)
|> Hexpds.DidGenerator.get_public_key()
|> Hexpds.DidGenerator.create_public_did_key() == expected_did
end
end
end
Loading