├── .formatter.exs ├── .github └── workflows │ └── elixir.yml ├── .gitignore ├── LICENSE ├── README.md ├── lib ├── curvy.ex └── curvy │ ├── curve.ex │ ├── key.ex │ ├── point.ex │ ├── signature.ex │ └── util.ex ├── media └── poster.png ├── mix.exs ├── mix.lock └── test ├── curvy ├── key_test.exs ├── signature_test.exs └── vector_test.exs ├── curvy_test.exs ├── test_helper.exs └── vectors ├── ecdh.json └── ecdsa.json /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.github/workflows/elixir.yml: -------------------------------------------------------------------------------- 1 | name: Elixir CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | name: OTP ${{matrix.otp}} / Elixir ${{matrix.elixir}} 13 | strategy: 14 | matrix: 15 | otp: ['24.x', '25.x'] 16 | elixir: ['1.12.3', '1.13.4', '1.14.2'] 17 | exclude: 18 | - otp: '25.x' 19 | elixir: '1.12.3' 20 | steps: 21 | - uses: actions/checkout@v2 22 | - uses: erlef/setup-beam@v1 23 | with: 24 | otp-version: ${{matrix.otp}} 25 | elixir-version: ${{matrix.elixir}} 26 | - run: mix deps.get 27 | - run: mix test -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # The directory Mix will write compiled artifacts to. 4 | /_build/ 5 | 6 | # If you run "mix test --cover", coverage assets end up here. 7 | /cover/ 8 | 9 | # The directory Mix downloads your dependencies sources to. 10 | /deps/ 11 | 12 | # Where third-party dependencies like ExDoc output generated docs. 13 | /doc/ 14 | 15 | # Ignore .fetch files in case you like to edit your project deps locally. 16 | /.fetch 17 | 18 | # If the VM crashes, it generates a dump, let's ignore it too. 19 | erl_crash.dump 20 | 21 | # Also ignore archive artifacts (built via "mix archive.build"). 22 | *.ez 23 | 24 | # Ignore package tarball (built via "mix hex.build"). 25 | curvy-*.tar 26 | 27 | 28 | # Temporary files for e.g. tests 29 | /tmp 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Curvy 2 | 3 | ![Curvy](https://raw.githubusercontent.com/libitx/curvy/main/media/poster.png) 4 | 5 | ![Hex.pm](https://img.shields.io/hexpm/v/curvy?color=informational) 6 | ![License](https://img.shields.io/github/license/libitx/curvy?color=informational) 7 | ![Build Status](https://img.shields.io/github/actions/workflow/status/libitx/curvy/elixir.yml?branch=main) 8 | 9 | Signatures and Bitcoin flavoured crypto written in pure Elixir. Curvy is an implementation of `secp256k1`, an elliptic curve that can be used in signature schemes, asymmetric encryption and ECDH shared secrets. 10 | 11 | ## Highlights 12 | 13 | * Pure Elixir implementation of `secp256k1` - no external dependencies 14 | * Fast ECDSA cryptography using Jacobian Point mathematics 15 | * Supports deterministic ECDSA signatures as per [RFC 6979](https://tools.ietf.org/html/rfc6979) 16 | * Securely generate random ECDSA keypairs 17 | * Compute ECDH shared secrets 18 | 19 | ## Installation 20 | 21 | The package can be installed by adding `curvy` to your list of dependencies in `mix.exs`. 22 | 23 | ```elixir 24 | def deps do 25 | [ 26 | {:curvy, "~> 0.3"} 27 | ] 28 | end 29 | ``` 30 | 31 | ## Usage 32 | 33 | For further examples, refer to the [full documentation](https://hexdocs.pm/curvy). 34 | 35 | ### 1. Key generation 36 | 37 | Create random ECDSA keypairs. 38 | 39 | ```elixir 40 | iex> key = Curvy.generate_key() 41 | %Curvy.Key{ 42 | crv: :secp256k1, 43 | point: %Curvy.Point{}, 44 | private_key: <<>> 45 | } 46 | ``` 47 | 48 | ECDSA Keypairs can by converted to public and private key binaries. 49 | 50 | ```elixir 51 | iex> Curvy.Key.to_privkey(key) 52 | <> 53 | 54 | iex> Curvy.Key.to_pubkey(key) 55 | <> 56 | 57 | iex> Curvy.Key.to_pubkey(key, compressed: false) 58 | <> 59 | ``` 60 | 61 | ### 2. Sign messages 62 | 63 | Sign arbitrary messages with a private key. Signatures are deterministic as per [RFC 6979](https://tools.ietf.org/html/rfc6979). 64 | 65 | ```elixir 66 | iex> sig = Curvy.sign("hello", key) 67 | <> 68 | 69 | iex> sig = Curvy.sign("hello", key, compact: true) 70 | <> 71 | 72 | iex> sig = Curvy.sign("hello", key, compact: true, encoding: :base64) 73 | "IEnXUDXZ3aghwXaq1zu9ax2zJj7N+O4gGREmWBmrldwrIb9B7QuicjwPrrv3ocPpxYO7uCxcw+DR/FcHR9b/YjM=" 74 | ``` 75 | 76 | ### 3. Verify signatures 77 | 78 | Verify a signature against the message and a public key. 79 | 80 | ```elixir 81 | iex> sig = Curvy.verify(sig, "hello", key) 82 | true 83 | 84 | iex> sig = Curvy.verify(sig, "hello", wrongkey) 85 | false 86 | 87 | # Returns :error if the signature cannot be decoded 88 | iex> sig = Curvy.verify("notasig", "hello", key) 89 | :error 90 | ``` 91 | 92 | ### 4. Recover the public key from a signature 93 | 94 | It's possible to recover the public key from a compact signature when given 95 | with the signed message. 96 | 97 | ```elixir 98 | iex> sig = Curvy.sign("hello", key, compact: true) 99 | iex> recovered = Curvy.recover_key(sig, "hello") 100 | iex> recovered.point == key.point 101 | true 102 | ``` 103 | 104 | The same can be done with DER encoded signatures if the recovery ID is known. 105 | 106 | ```elixir 107 | iex> {sig, recovery_id} = Curvy.sign("hello", key, recovery: true) 108 | iex> recovered = Curvy.recover_key(sig, "hello", recovery_id: recovery_id) 109 | iex> recovered.point == key.point 110 | true 111 | ``` 112 | 113 | ### 5. ECDH shared secrets 114 | 115 | ECDH shared secrets are computed by multiplying a public key with a private 116 | key. The operation yields the same result in both directions. 117 | 118 | ```elixir 119 | iex> s1 = Curvy.get_shared_secret(key1, key2) 120 | iex> s2 = Curvy.get_shared_secret(key2, key1) 121 | iex> s1 == s2 122 | true 123 | ``` 124 | 125 | 126 | 127 | For more examples, refer to the [full documentation](https://hexdocs.pm/curvy). 128 | 129 | ## Disclaimer 130 | 131 | The are many warnings that you should never try to implement well-known (and known to be secure) crypto algorithms yourself. Well guess what, that's exactly what I've done here. I am **not** a cryptographer nor a mathmetician. Proceed at your own risk. If you're after the most performant and battle tested Bitcoin library, use the [`libsecp256k1`](https://hex.pm/packages/libsecp256k1) NIF bindings. 132 | 133 | This library offers a simpler and smaller interface for common functionality. Being writting purely in Elixir without any dependencies, it is a lighter-weight option without the compilation complexities NIF bindings may bring. 134 | 135 | I am grateful to the authors of the following open source libraries I have referred to extensively in creating this library: 136 | 137 | * [noble-secp256k1](https://github.com/paulmillr/noble-secp256k1) - JS 138 | * [starbank-ecdsa](https://github.com/starkbank/ecdsa-elixir) - Elixir 139 | * [bsv](https://github.com/moneybutton/bsv) - JS 140 | 141 | ## License 142 | 143 | Curvy is open source and released under the [Apache-2 License](https://github.com/libitx/curvy/blob/master/LICENSE). 144 | 145 | © Copyright 2021 [Chronos Labs Ltd](https://www.chronoslabs.net). 146 | -------------------------------------------------------------------------------- /lib/curvy.ex: -------------------------------------------------------------------------------- 1 | defmodule Curvy do 2 | @moduledoc """ 3 | ![Curvy](https://raw.githubusercontent.com/libitx/curvy/main/media/poster.png) 4 | 5 | ![License](https://img.shields.io/github/license/libitx/curvy?color=informational) 6 | 7 | Signatures and Bitcoin flavoured crypto written in pure Elixir. Curvy is an 8 | implementation of `secp256k1`, an elliptic curve that can be used in signature 9 | schemes, asymmetric encryption and ECDH shared secrets. 10 | 11 | ## Highlights 12 | 13 | * Pure Elixir implementation of `secp256k1` - no external dependencies 14 | * Fast ECDSA cryptography using Jacobian Point mathematics 15 | * Supports deterministic ECDSA signatures as per [RFC 6979](https://tools.ietf.org/html/rfc6979) 16 | * Securely generate random ECDSA keypairs 17 | * Compute ECDH shared secrets 18 | 19 | ## Installation 20 | 21 | The package can be installed by adding `curvy` to your list of dependencies in 22 | `mix.exs`. 23 | 24 | def deps do 25 | [ 26 | {:curvy, "~> #{ Mix.Project.config[:version] }"} 27 | ] 28 | end 29 | 30 | ## Usage 31 | 32 | ### 1. Key generation 33 | 34 | Create random ECDSA keypairs. 35 | 36 | iex> key = Curvy.generate_key() 37 | %Curvy.Key{ 38 | crv: :secp256k1, 39 | point: %Curvy.Point{}, 40 | private_key: <<>> 41 | } 42 | 43 | [`ECDSA Keypairs`](`t:Curvy.Key.t`) can by converted to public and private key 44 | binaries. 45 | 46 | iex> Curvy.Key.to_privkey(key) 47 | <> 48 | 49 | iex> Curvy.Key.to_pubkey(key) 50 | <> 51 | 52 | iex> Curvy.Key.to_pubkey(key, compressed: false) 53 | <> 54 | 55 | ### 2. Sign messages 56 | 57 | Sign arbitrary messages with a private key. Signatures are deterministic as 58 | per [RFC 6979](https://tools.ietf.org/html/rfc6979). 59 | 60 | iex> sig = Curvy.sign("hello", key) 61 | <> 62 | 63 | iex> sig = Curvy.sign("hello", compact: true) 64 | <> 65 | 66 | iex> sig = Curvy.sign("hello", compact: true, encoding: :base64) 67 | "IEnXUDXZ3aghwXaq1zu9ax2zJj7N+O4gGREmWBmrldwrIb9B7QuicjwPrrv3ocPpxYO7uCxcw+DR/FcHR9b/YjM=" 68 | 69 | ### 3. Verify signatures 70 | 71 | Verify a signature against the message and a public key. 72 | 73 | iex> sig = Curvy.verify(sig, "hello", key) 74 | true 75 | 76 | iex> sig = Curvy.verify(sig, "hello", wrongkey) 77 | false 78 | 79 | # Returns :error if the signature cannot be decoded 80 | iex> sig = Curvy.verify("notasig", "hello", key) 81 | :error 82 | 83 | ### 4. Recover the public key from a signature 84 | 85 | It's possible to recover the public key from a compact signature when given 86 | with the signed message. 87 | 88 | iex> sig = Curvy.sign("hello", key, compact: true) 89 | iex> recovered = Curvy.recover_key(sig, "hello") 90 | iex> recovered.point == key.point 91 | true 92 | 93 | The same can be done with DER encoded signatures if the recovery ID is known. 94 | 95 | iex> {sig, recovery_id} = Curvy.sign("hello", key, recovery: true) 96 | iex> recovered = Curvy.recover_key(sig, "hello", recovery_id: recovery_id) 97 | iex> recovered.point == key.point 98 | true 99 | 100 | ### 5. ECDH shared secrets 101 | 102 | ECDH shared secrets are computed by multiplying a public key with a private 103 | key. The operation yields the same result in both directions. 104 | 105 | iex> s1 = Curvy.get_shared_secret(key1, key2) 106 | iex> s2 = Curvy.get_shared_secret(key2, key1) 107 | iex> s1 == s2 108 | true 109 | 110 | """ 111 | import Bitwise 112 | alias Curvy.{Curve, Key, Point, Signature} 113 | import Curvy.Util, only: [encode: 2, decode: 2, inv: 2, mod: 2] 114 | 115 | @crv Curve.secp256k1 116 | 117 | 118 | @doc """ 119 | Creates a new random ESCDA keypair. 120 | """ 121 | @spec generate_key() :: Key.t 122 | def generate_key(), do: Key.generate() 123 | 124 | 125 | @doc """ 126 | Computes an ECDH shared secret from the first given key's private key and 127 | the second's public key. 128 | 129 | Returns a 32 byte binary. 130 | 131 | ## Accepted options 132 | 133 | * `:encoding` - Optionally encode the returned secret as `:base64` or `:hex`. 134 | """ 135 | @spec get_shared_secret(Key.t | binary, Key.t | binary) :: binary 136 | def get_shared_secret(privkey, pubkey, opts \\ []) 137 | 138 | def get_shared_secret(privkey, pubkey, opts) when is_binary(privkey), 139 | do: get_shared_secret(Key.from_privkey(privkey), pubkey, opts) 140 | 141 | def get_shared_secret(privkey, pubkey, opts) when is_binary(pubkey), 142 | do: get_shared_secret(privkey, Key.from_pubkey(pubkey), opts) 143 | 144 | def get_shared_secret(%Key{privkey: <>}, %Key{point: point}, opts) do 145 | encoding = Keyword.get(opts, :encoding) 146 | x = point 147 | |> Point.mul(d) 148 | |> Map.get(:x) 149 | encode(<>, encoding) 150 | end 151 | 152 | 153 | @doc """ 154 | Recovers the public key from the signature and signed message. 155 | 156 | Returns an [`ECDSA Keypair`](`t:t`) struct, without the privkey value. 157 | 158 | If recovering fom a DER encoded signature, the [`Recovery ID`](`Signature.recovery_id`) 159 | returned from `Curvy.sign(msg, key, recovery: true)` must be passed as an 160 | option. If recovering from a compact signature the recovery ID is already 161 | encoded in the signature. 162 | 163 | ## Accepted options 164 | 165 | * `:encoding` - Optionally decode the given signature as `:base64` or `:hex`. 166 | * `:hash` - Digest algorithm to hash the message with. Default is `:sha256`. 167 | * `:recovery_id` - The signature [`Recovery ID`](`Signature.recovery_id`). 168 | """ 169 | @spec recover_key(Signature.t | binary, binary, keyword) :: Key.t | :error 170 | def recover_key(sig, message, opts \\ []) 171 | 172 | def recover_key(data, message, opts) when is_binary(data) do 173 | encoding = Keyword.get(opts, :encoding) 174 | with {:ok, data} <- decode(data, encoding), 175 | %Signature{} = sig <- Signature.parse(data) 176 | do 177 | opts = case data do 178 | <> when (prefix - 27 - 4) < 0 -> 179 | Keyword.put(opts, :compressed, false) 180 | _ -> 181 | opts 182 | end 183 | recover_key(sig, message, opts) 184 | end 185 | end 186 | 187 | def recover_key(%Signature{recid: recid} = sig, message, opts) do 188 | with recid when recid in 0..3 <- Keyword.get(opts, :recovery_id, recid) do 189 | digest = Keyword.get(opts, :hash, :sha256) 190 | e = message 191 | |> hash_message(digest) 192 | |> :binary.decode_unsigned() 193 | 194 | sig 195 | |> Signature.normalize() 196 | |> Point.from_signature(e, recid) 197 | |> Key.from_point(Keyword.take(opts, [:compressed])) 198 | else 199 | _ -> 200 | raise "Recovery ID not in range 0..3" 201 | end 202 | end 203 | 204 | 205 | @doc """ 206 | Signs the message with the given private key. 207 | 208 | Returns a DER encoded or compact signature binary. 209 | 210 | ## Accepted options 211 | 212 | * `:hash` - Digest algorithm to hash the message with. Default is `:sha256`. 213 | * `:normalize` - Normalize the signature by enforcing low-S. Default is `true`. 214 | * `:compact` - Return a compact 65 byte signature. Default is `false`. 215 | * `:encoding` - Optionally encode the returned signature as `:base64` or `:hex`. 216 | * `:recovery` - Return the signature in a tuple paired with a recovery ID. Default is `false`. 217 | * `:k` - Optionally provide a signing secret `K` value, as a 256 bit integer or binary. 218 | """ 219 | @spec sign(binary, Key.t | binary, keyword) :: binary 220 | def sign(message, privkey, opts \\ []) 221 | 222 | def sign(message, %Key{privkey: privkey, compressed: compressed}, opts) 223 | when is_binary(privkey) 224 | do 225 | opts = Keyword.put_new(opts, :compressed, compressed) 226 | sign(message, privkey, opts) 227 | end 228 | 229 | def sign(message, <>, opts) do 230 | digest = Keyword.get(opts, :hash, :sha256) 231 | encoding = Keyword.get(opts, :encoding) 232 | hash = hash_message(message, digest) 233 | e = :binary.decode_unsigned(hash) 234 | 235 | {q, r, s} = case Keyword.get(opts, :k) do 236 | k when is_integer(k) and 0 < k and k < @crv.n -> 237 | get_qrs(e, d, k) 238 | <> -> 239 | get_qrs(e, d, k) 240 | nil -> 241 | deterministic_k(hash, d) 242 | end 243 | 244 | recid = get_recovery_id(q, r) 245 | 246 | sig = %Signature{r: r, s: s, recid: recid} 247 | |> maybe_normalize(opts) 248 | 249 | sig 250 | |> maybe_compact(opts) 251 | |> encode(encoding) 252 | |> maybe_recovery(sig, opts) 253 | end 254 | 255 | 256 | @doc """ 257 | Verifies the signature against the given message and public key. 258 | 259 | Returns a boolean. 260 | 261 | ## Accepted options 262 | 263 | * `:encoding` - Optionally decode the given signature as `:base64` or `:hex`. 264 | * `:hash` - Digest algorithm to hash the message with. Default is `:sha256`. 265 | """ 266 | @spec verify(Signature.t | binary, binary, Key.t | binary, keyword) :: boolean | :error 267 | def verify(sig, message, pubkey, opts \\ []) 268 | 269 | def verify(sig, message, pubkey, opts) when is_binary(pubkey), 270 | do: verify(sig, message, Key.from_pubkey(pubkey), opts) 271 | 272 | def verify(sig, message, %Key{} = pubkey, opts) when is_binary(sig) do 273 | encoding = Keyword.get(opts, :encoding) 274 | with {:ok, sig} <- decode(sig, encoding), 275 | %Signature{} = sig <- Signature.parse(sig) 276 | do 277 | verify(sig, message, pubkey, opts) 278 | end 279 | end 280 | 281 | def verify(%Signature{r: r, s: s}, message, %Key{point: point}, opts) do 282 | digest = Keyword.get(opts, :hash, :sha256) 283 | e = message 284 | |> hash_message(digest) 285 | |> :binary.decode_unsigned() 286 | 287 | i = inv(s, @crv.n) 288 | 289 | p = Point.mul(@crv[:G], mod(e * i, @crv.n)) 290 | q = Point.mul(point, mod(r * i, @crv.n)) 291 | 292 | Point.add(p, q) 293 | |> Map.get(:x) 294 | |> Kernel.==(r) 295 | end 296 | 297 | 298 | # Calculates the QRS values 299 | defp get_qrs(e, d, k) do 300 | q = Point.mul(@crv[:G], k) 301 | r = mod(q.x, @crv.n) 302 | s = (inv(k, @crv.n) * (e + r * d)) |> mod(@crv.n) 303 | 304 | {q, r, s} 305 | end 306 | 307 | 308 | # Hashes the message with the given digest algorith 309 | defp hash_message(message, digest) when digest in [:sha256, :sha384, :sha512], 310 | do: :crypto.hash(digest, message) 311 | 312 | defp hash_message(message, _digest), do: message 313 | 314 | 315 | # Implements RFC 6979 and returns QRS values from deterministically generated K 316 | defp deterministic_k(hash, d) do 317 | e = :binary.decode_unsigned(hash) 318 | v = :binary.copy(<<1>>, 32) 319 | k = :binary.copy(<<0>>, 32) 320 | k = :crypto.mac(:hmac, :sha256, k, <>) 321 | v = :crypto.mac(:hmac, :sha256, k, v) 322 | k = :crypto.mac(:hmac, :sha256, k, <>) 323 | v = :crypto.mac(:hmac, :sha256, k, v) 324 | 325 | Enum.reduce_while 0..1000, {k, v}, fn i, {k, v} -> 326 | if i == 1000, do: throw "Tried 1000 k values, all were invalid" 327 | v = :crypto.mac(:hmac, :sha256, k, v) 328 | 329 | case v do 330 | <> when 0 < t and t < @crv.n -> 331 | case get_qrs(e, d, t) do 332 | {_, r, s} when r == 0 or s == 0 -> 333 | {:cont, {k, v}} 334 | {q, r, s} -> 335 | {:halt, {q, r, s}} 336 | end 337 | 338 | _ -> 339 | k = :crypto.mac(:hmac, :sha256, k, <>) 340 | v = :crypto.mac(:hmac, :sha256, k, v) 341 | {:cont, {k, v}} 342 | end 343 | end 344 | end 345 | 346 | 347 | # Get the recovery ID from the point and R value 348 | defp get_recovery_id(%{x: x, y: y}, r) when x == r, do: bor(0, band(y, 1)) 349 | defp get_recovery_id(%{x: _x, y: y}, _r), do: bor(2, band(y, 1)) 350 | 351 | 352 | # Normalizes the given signature if opted for 353 | defp maybe_normalize(%Signature{} = sig, opts) do 354 | case Keyword.get(opts, :normalize, true) do 355 | opt when opt in [false, nil] -> 356 | sig 357 | _ -> 358 | Signature.normalize(sig) 359 | end 360 | end 361 | 362 | 363 | # Returns compact or der encoded signature 364 | defp maybe_compact(%Signature{} = sig, opts) do 365 | case Keyword.get(opts, :compact, false) do 366 | opt when opt in [false, nil] -> 367 | Signature.to_der(sig) 368 | _ -> 369 | Signature.to_compact(sig, Keyword.take(opts, [:compressed])) 370 | end 371 | end 372 | 373 | 374 | # Returns the signature with recovery is of opted for 375 | defp maybe_recovery(encoded_sig, %Signature{recid: recid}, opts) 376 | when is_integer(recid) 377 | do 378 | case Keyword.get(opts, :recovery) do 379 | true -> {encoded_sig, recid} 380 | _ -> encoded_sig 381 | end 382 | end 383 | 384 | defp maybe_recovery(encoded_sig, _sig, _opts), do: encoded_sig 385 | 386 | end 387 | -------------------------------------------------------------------------------- /lib/curvy/curve.ex: -------------------------------------------------------------------------------- 1 | defmodule Curvy.Curve do 2 | @moduledoc """ 3 | Describes the secp256k1 elliptic curve. 4 | """ 5 | alias Curvy.Point 6 | 7 | @typedoc "ECDSA Curve Parameters" 8 | @type t :: %{ 9 | p: integer, 10 | a: integer, 11 | b: integer, 12 | G: Point.t, 13 | n: integer, 14 | h: integer 15 | } 16 | 17 | @secp256k1 %{ 18 | p: 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F, 19 | a: 0x0000000000000000000000000000000000000000000000000000000000000000, 20 | b: 0x0000000000000000000000000000000000000000000000000000000000000007, 21 | G: %Point{ 22 | x: 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 23 | y: 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 24 | }, 25 | n: 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141, 26 | h: 0x01 27 | } 28 | 29 | 30 | @doc """ 31 | Returns the secp256k1 curve parameters. 32 | """ 33 | @spec secp256k1() :: t 34 | def secp256k1(), do: @secp256k1 35 | 36 | end 37 | -------------------------------------------------------------------------------- /lib/curvy/key.ex: -------------------------------------------------------------------------------- 1 | defmodule Curvy.Key do 2 | @moduledoc """ 3 | Module used to create ECDSA keypairs and convert to private and public key 4 | binaries. 5 | """ 6 | alias Curvy.{Curve, Point} 7 | 8 | defstruct crv: :secp256k1, 9 | point: %Point{}, 10 | privkey: nil, 11 | compressed: true 12 | 13 | 14 | @typedoc """ 15 | ECDSA Keypair. 16 | 17 | Always contains the `t:Point.t` coordinates and optionally a private key binary. 18 | """ 19 | @type t :: %__MODULE__{ 20 | crv: atom, 21 | point: Point.t, 22 | privkey: binary | nil, 23 | compressed: boolean 24 | } 25 | 26 | @crv Curve.secp256k1 27 | 28 | 29 | @doc """ 30 | Creates a new random ESCDA keypair. 31 | """ 32 | @spec generate(keyword) :: t 33 | def generate(opts \\ []) do 34 | compressed = Keyword.get(opts, :compressed, true) 35 | {pubkey, privkey} = :crypto.generate_key(:ecdh, :secp256k1) 36 | <<_::integer, x::big-size(256), y::big-size(256)>> = pubkey 37 | 38 | %__MODULE__{ 39 | point: %Point{x: x, y: y}, 40 | privkey: privkey, 41 | compressed: compressed 42 | } 43 | end 44 | 45 | 46 | @doc """ 47 | Converts the given private key binary to a [`ECDSA Keypair`](`t:t`). 48 | """ 49 | @spec from_privkey(binary, keyword) :: t 50 | def from_privkey(<>, opts \\ []) do 51 | compressed = Keyword.get(opts, :compressed, true) 52 | {pubkey, _privkey} = :crypto.generate_key(:ecdh, :secp256k1, privkey) 53 | <<_::integer, x::big-size(256), y::big-size(256)>> = pubkey 54 | 55 | %__MODULE__{ 56 | point: %Point{x: x, y: y}, 57 | privkey: privkey, 58 | compressed: compressed 59 | } 60 | end 61 | 62 | 63 | @doc """ 64 | Converts the given public key binary to a [`ECDSA Keypair`](`t:t`) struct 65 | without a private key. 66 | """ 67 | @spec from_pubkey(binary) :: t 68 | def from_pubkey(pubkey) 69 | 70 | def from_pubkey(<<_::integer, x::big-size(256), y::big-size(256)>>), 71 | do: %__MODULE__{point: %Point{x: x, y: y}, compressed: false} 72 | 73 | def from_pubkey(<>) do 74 | y = x 75 | |> :crypto.mod_pow(3, @crv.p) 76 | |> :binary.decode_unsigned() 77 | |> Kernel.+(7) 78 | |> rem(@crv.p) 79 | |> :crypto.mod_pow(Integer.floor_div(@crv.p + 1, 4), @crv.p) 80 | |> :binary.decode_unsigned() 81 | 82 | y = if rem(y, 2) != rem(prefix, 2), do: @crv.p - y, else: y 83 | 84 | %__MODULE__{point: %Point{x: x, y: y}, compressed: true} 85 | end 86 | 87 | 88 | @doc """ 89 | Converts the given [`Point`](`Point:t`) to a [`ECDSA Keypair`](`t:t`) struct 90 | without a private key. 91 | """ 92 | @spec from_point(Point.t, keyword) :: t 93 | def from_point(%Point{} = point, opts \\ []) do 94 | compressed = Keyword.get(opts, :compressed, true) 95 | %__MODULE__{point: point, compressed: compressed} 96 | end 97 | 98 | 99 | @doc """ 100 | Returns the 32 byte private key binary from the given [`ECDSA Keypair`](`t:t`). 101 | """ 102 | def to_privkey(%__MODULE__{privkey: privkey}), do: privkey 103 | 104 | 105 | @doc """ 106 | Returns the public key binary from the given [`ECDSA Keypair`](`t:t`) in either 107 | compressed or uncompressed form. 108 | 109 | ## Accepted options 110 | 111 | * `:compressed` - Return a 32 byte compressed public key. Default is `true`. 112 | """ 113 | def to_pubkey(%__MODULE__{point: %Point{x: x, y: y}, compressed: compressed}, opts \\ []) do 114 | case Keyword.get(opts, :compressed, compressed) do 115 | true -> 116 | prefix = if rem(y, 2) == 0, do: 0x02, else: 0x03 117 | <> 118 | false -> 119 | <<4, x::big-size(256), y::big-size(256)>> 120 | end 121 | end 122 | 123 | end 124 | -------------------------------------------------------------------------------- /lib/curvy/point.ex: -------------------------------------------------------------------------------- 1 | defmodule Curvy.Point do 2 | @moduledoc """ 3 | Module used for manipulating ECDSA point coordinates. 4 | """ 5 | import Bitwise 6 | import Curvy.Util, only: [mod: 2, inv: 2, ipow: 2] 7 | alias Curvy.{Curve, Key, Signature} 8 | 9 | defstruct [:x, :y] 10 | 11 | @typedoc "Point Coordinates" 12 | @type t :: %__MODULE__{ 13 | x: integer, 14 | y: integer 15 | } 16 | 17 | @typedoc "Jacobian Point Coordiantes" 18 | @type jacobian :: %{ 19 | x: integer, 20 | y: integer, 21 | z: integer 22 | } 23 | 24 | @crv Curve.secp256k1 25 | 26 | 27 | @doc """ 28 | Converts the signature to a [`Point`](`t:t`) using the given hash integer and 29 | recovery ID. 30 | """ 31 | @spec from_signature(Signature.t, integer, Signature.recovery_id) :: t | :error 32 | def from_signature(%Signature{r: r, s: s}, _e, _recid) 33 | when r == 0 or s == 0, 34 | do: :error 35 | 36 | def from_signature(%Signature{r: r, s: s}, e, recid) do 37 | rinv = inv(r, @crv.n) 38 | prefix = 2 + band(recid, 1) 39 | 40 | sp = <> 41 | |> Key.from_pubkey() 42 | |> Map.get(:point) 43 | |> mul(s) 44 | 45 | hg = @crv[:G] 46 | |> mul(e) 47 | |> negate() 48 | 49 | sp 50 | |> add(hg) 51 | |> mul(rinv) 52 | end 53 | 54 | 55 | @doc """ 56 | Adds two elliptic curve points. 57 | 58 | Returns a [`Point`](`t:t`). 59 | """ 60 | @spec add(t, t) :: t 61 | def add(%__MODULE__{} = point, %__MODULE__{} = other) do 62 | jacobian_add(to_jacobian(point), to_jacobian(other)) 63 | |> from_jacobian() 64 | end 65 | 66 | 67 | @doc """ 68 | Doubles an elliptic curve point. 69 | 70 | Returns a [`Point`](`t:t`). 71 | """ 72 | @spec double(t) :: t 73 | def double(%__MODULE__{} = point) do 74 | point 75 | |> to_jacobian() 76 | |> jacobian_double() 77 | |> from_jacobian() 78 | end 79 | 80 | 81 | @doc """ 82 | Compares two elliptic curve points. 83 | 84 | Returns a `t:boolean`. 85 | """ 86 | @spec equals(point :: t, other :: t) :: boolean 87 | def equals(%__MODULE__{} = p, %__MODULE__{} = q) do 88 | p.x == q.x and p.y == q.y 89 | end 90 | 91 | 92 | @doc """ 93 | Mutiplies an elliptic curve point with the given scalar. 94 | 95 | Returns a [`Point`](`t:t`). 96 | """ 97 | @spec mul(t, integer) :: t 98 | def mul(%__MODULE__{} = point, scalar) do 99 | point 100 | |> to_jacobian() 101 | |> jacobian_mul(scalar) 102 | |> from_jacobian() 103 | end 104 | 105 | 106 | @doc """ 107 | Flips the elliptic curve point to `(x, -y)`. 108 | 109 | Returns a [`Point`](`t:t`). 110 | """ 111 | @spec negate(point :: t) :: t 112 | def negate(%__MODULE__{x: x, y: y}), 113 | do: %__MODULE__{x: x, y: mod(-y, @crv.p)} 114 | 115 | 116 | @doc """ 117 | Subtracts the second elliptic curve point from the first. 118 | 119 | Returns a [`Point`](`t:t`). 120 | """ 121 | @spec subtract(t, t) :: t 122 | def subtract(%__MODULE__{} = point, %__MODULE__{} = other), 123 | do: add(point, negate(other)) 124 | 125 | 126 | # Converts the Point to Jacobian Point Coordianets 127 | defp to_jacobian(%__MODULE__{x: x, y: y}), do: %{x: x, y: y, z: 1} 128 | 129 | 130 | # Converts the Jacobian Point to Affine Coordiantes 131 | defp from_jacobian(%{x: x, y: y, z: z}) do 132 | z = inv(z, @crv.p) 133 | %__MODULE__{ 134 | x: (x * ipow(z, 2)) |> mod(@crv.p), 135 | y: (y * ipow(z, 3)) |> mod(@crv.p) 136 | } 137 | end 138 | 139 | 140 | # Fast way to add two elliptic curve points 141 | defp jacobian_add(%{y: py} = p, %{y: qy}) when py == 0 or qy == 0, do: p 142 | defp jacobian_add(%{} = p, %{} = q) do 143 | u1 = (p.x * ipow(q.z, 2)) |> mod(@crv.p) 144 | u2 = (q.x * ipow(p.z, 2)) |> mod(@crv.p) 145 | s1 = (p.y * ipow(q.z, 3)) |> mod(@crv.p) 146 | s2 = (q.y * ipow(p.z, 3)) |> mod(@crv.p) 147 | 148 | cond do 149 | u1 == u2 and s1 != s2 -> 150 | %{x: 0, y: 0, z: 1} 151 | 152 | u1 == u2 -> 153 | jacobian_double(p) 154 | 155 | true -> 156 | h = u2 - u1 157 | r = s2 - s1 158 | h2 = mod(h * h, @crv.p) 159 | h3 = mod(h * h2, @crv.p) 160 | u1h2 = mod(u1 * h2, @crv.p) 161 | x = (ipow(r, 2) - h3 - 2 * u1h2) |> mod(@crv.p) 162 | y = (r * (u1h2 - x) - s1 * h3) |> mod(@crv.p) 163 | z = (h * p.z * q.z) |> mod(@crv.p) 164 | %{x: x, y: y, z: z} 165 | end 166 | end 167 | 168 | 169 | # Fast way to doubles an elliptic curve point 170 | defp jacobian_double(%{y: 0}), do: %{x: 0, y: 0, z: 0} 171 | defp jacobian_double(%{} = p) do 172 | ysq = ipow(p.y, 2) |> mod(@crv.p) 173 | s = (4 * p.x * ysq) |> mod(@crv.p) 174 | m = (3 * ipow(p.x, 2) + @crv.a * ipow(p.z, 4)) |> mod(@crv.p) 175 | x = (ipow(m, 2) - 2 * s) |> mod(@crv.p) 176 | y = (m * (s - x) - 8 * ipow(ysq, 2)) |> mod(@crv.p) 177 | z = (2 * p.y * p.z) |> mod(@crv.p) 178 | %{x: x, y: y, z: z} 179 | end 180 | 181 | 182 | # Fast way to multiply the point with a scalar 183 | defp jacobian_mul(%{}, 0), do: %{x: 0, y: 0, z: 1} 184 | defp jacobian_mul(%{y: 0}, s) when s == 1, do: %{x: 0, y: 0, z: 1} 185 | defp jacobian_mul(%{} = p, s) when s == 1, do: p 186 | defp jacobian_mul(%{y: 0}, s) when s < 0 or @crv.n <= s, do: %{x: 0, y: 0, z: 1} 187 | defp jacobian_mul(%{} = p, s) when s < 0 or @crv.n <= s, do: jacobian_mul(p, mod(s, @crv.n)) 188 | defp jacobian_mul(%{y: 0}, s) when rem(s, 2) == 0, do: %{x: 0, y: 0, z: 1} 189 | defp jacobian_mul(%{} = p, s) when rem(s, 2) == 0, do: jacobian_mul(p, div(s, 2)) |> jacobian_double() 190 | defp jacobian_mul(%{y: 0}, _s), do: %{x: 0, y: 0, z: 1} 191 | defp jacobian_mul(%{} = p, s), do: jacobian_mul(p, div(s, 2)) |> jacobian_double() |> jacobian_add(p) 192 | 193 | end 194 | -------------------------------------------------------------------------------- /lib/curvy/signature.ex: -------------------------------------------------------------------------------- 1 | defmodule Curvy.Signature do 2 | @moduledoc """ 3 | Module for converting signature R and S values to DER encoded or compact 4 | binaries. 5 | """ 6 | import Bitwise 7 | alias Curvy.Curve 8 | 9 | defstruct crv: :secp256k1, 10 | r: nil, 11 | s: nil, 12 | recid: nil 13 | 14 | @typedoc "ECDSA Signature" 15 | @type t :: %__MODULE__{ 16 | crv: atom, 17 | r: integer, 18 | s: integer, 19 | recid: recovery_id | nil 20 | } 21 | 22 | @typedoc "Recovery ID" 23 | @type recovery_id :: 0 | 1 | 2 | 3 24 | 25 | @crv Curve.secp256k1 26 | 27 | 28 | @doc """ 29 | Parsed the given binary signature in a [`Signature`](`t:t`) struct. 30 | 31 | Parsed DER encoded and compact signatures. Returns `:error` if unable to parse. 32 | """ 33 | @spec parse(binary) :: t | :error 34 | def parse(<<0x30, _len, 0x02, rlen, rbin::bytes-size(rlen), 0x02, slen, sbin::bytes-size(slen)>>) do 35 | %__MODULE__{ 36 | r: :binary.decode_unsigned(rbin), 37 | s: :binary.decode_unsigned(sbin) 38 | } 39 | end 40 | 41 | def parse(<>) do 42 | recid = case prefix - 27 - 4 do 43 | recid when recid < 0 -> 44 | recid + 4 45 | recid -> 46 | recid 47 | end 48 | %__MODULE__{r: r, s: s, recid: recid} 49 | end 50 | 51 | def parse(_sig), do: :error 52 | 53 | 54 | @doc """ 55 | Normalizes the signature by enforcing Low-S values. 56 | 57 | Returns a [`Signature`](`t:t`). 58 | 59 | See [BIP 62](https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki) 60 | for more info. 61 | """ 62 | @spec normalize(t) :: t 63 | def normalize(%__MODULE__{s: s} = sig) when s > bsr(@crv.n, 1) do 64 | sig 65 | |> Map.put(:s, @crv.n - s) 66 | |> case do 67 | %__MODULE__{recid: recid} = sig when recid in 0..3 -> 68 | Map.put(sig, :recid, Bitwise.bxor(recid, 1)) 69 | sig -> 70 | sig 71 | end 72 | end 73 | 74 | def normalize(%__MODULE__{} = sig), do: sig 75 | 76 | 77 | @doc """ 78 | Returns the signature as a DER-encoded binary. 79 | """ 80 | @spec to_der(t) :: binary 81 | def to_der(%__MODULE__{r: r, s: s}, _opts \\ []) do 82 | rbin = der_encode_int(r) 83 | sbin = der_encode_int(s) 84 | rlen = byte_size(rbin) 85 | slen = byte_size(sbin) 86 | 87 | << 88 | 0x30, # header 89 | 2 + rlen + 2 + slen, # length 90 | 0x02, # r header 91 | rlen, # r length 92 | rbin::binary, # r 93 | 0x02, # s header 94 | slen, # s length 95 | sbin::binary # s 96 | >> 97 | end 98 | 99 | 100 | @doc """ 101 | Returns the signature as a 65 byte compact binary. 102 | """ 103 | @spec to_compact(t, keyword) :: binary 104 | def to_compact(%__MODULE__{r: r, s: s, recid: recid}, opts \\ []) do 105 | with recid when recid in 0..3 <- Keyword.get(opts, :recovery_id, recid) do 106 | prefix = case Keyword.get(opts, :compressed, true) do 107 | true -> recid + 27 + 4 108 | false -> recid + 27 109 | end 110 | 111 | << 112 | prefix, # recovery 113 | r::big-size(256), # r 114 | s::big-size(256) # s 115 | >> 116 | else 117 | _ -> 118 | raise "Recovery ID not in range 0..3" 119 | end 120 | end 121 | 122 | 123 | # DER encodes the given integer 124 | defp der_encode_int(int) when is_integer(int) do 125 | <> = bin = :binary.encode_unsigned(int) 126 | case band(n, 0x80) do 127 | 0 -> bin 128 | _ -> <<0, bin::binary>> 129 | end 130 | end 131 | 132 | end 133 | -------------------------------------------------------------------------------- /lib/curvy/util.ex: -------------------------------------------------------------------------------- 1 | defmodule Curvy.Util do 2 | @moduledoc """ 3 | Utility module for common and shared functions. 4 | """ 5 | 6 | @doc """ 7 | Decodes the given binary with the specified encoding scheme. 8 | 9 | Accepts `:base64` or `:hex`, or will return the binary as is. 10 | """ 11 | @spec decode(binary, atom) :: {:ok, binary} | {:error, any} 12 | def decode(data, enc) when enc in [:base64, :b64], do: Base.decode64(data) 13 | def decode(data, :hex), do: Base.decode16(data, case: :mixed) 14 | def decode(data, _), do: {:ok, data} 15 | 16 | 17 | @doc """ 18 | Encodes the given binary with the specified encoding scheme. 19 | 20 | Accepts `:base64` or `:hex`, or will return the binary as is. 21 | """ 22 | @spec encode(binary, atom) :: binary 23 | def encode(data, enc) when enc in [:base64, :b64], do: Base.encode64(data) 24 | def encode(data, :hex), do: Base.encode16(data, case: :lower) 25 | def encode(data, _), do: data 26 | 27 | 28 | @doc """ 29 | Invert operation. 30 | """ 31 | @spec inv(integer, integer) :: integer 32 | def inv(x, _n) when x == 0, do: 0 33 | def inv(x, n), do: inv_op(1, 0, mod(x, n), n) 34 | 35 | 36 | @doc """ 37 | Inverse power operation. 38 | """ 39 | @spec ipow(integer, integer) :: integer 40 | def ipow(base, p, acc \\ 1) 41 | def ipow(base, p, acc) when p > 0, do: ipow(base, p - 1, base * acc) 42 | def ipow(_base, _p, acc), do: acc 43 | 44 | 45 | @doc """ 46 | Modulo operation. Returns the remainder after x is divided by n. 47 | """ 48 | @spec mod(integer, integer) :: integer 49 | def mod(x, n), do: rem(x, n) |> correct_neg_mod(n) 50 | 51 | 52 | # Correct mod if negative 53 | defp correct_neg_mod(r, n) when r < 0, do: r + n 54 | defp correct_neg_mod(r, _n), do: r 55 | 56 | 57 | # Recursive inv function 58 | defp inv_op(lm, hm, low, high) when low > 1 do 59 | r = div(high, low) 60 | inv_op(hm - lm * r, lm, high - low * r, low) 61 | end 62 | 63 | defp inv_op(lm, _hm, _low, _high), do: lm 64 | 65 | end 66 | -------------------------------------------------------------------------------- /media/poster.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/libitx/curvy/efb2271671788725f0bc5a62a2744b580cabc53e/media/poster.png -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Curvy.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :curvy, 7 | version: "0.3.1", 8 | elixir: "~> 1.11", 9 | start_permanent: Mix.env() == :prod, 10 | deps: deps(), 11 | name: "Curvy", 12 | description: "Curvy is a pure Elixir implementation of secp256k1 for ECDSA signatures and Bitcoin flavoured crypto.", 13 | source_url: "https://github.com/libitx/curvy", 14 | docs: [ 15 | main: "Curvy" 16 | ], 17 | package: [ 18 | name: "curvy", 19 | files: ~w(lib .formatter.exs mix.exs README.md LICENSE), 20 | licenses: ["Apache-2.0"], 21 | links: %{ 22 | "GitHub" => "https://github.com/libitx/curvy" 23 | } 24 | ] 25 | ] 26 | end 27 | 28 | # Run "mix help compile.app" to learn about applications. 29 | def application do 30 | [ 31 | extra_applications: [:crypto] 32 | ] 33 | end 34 | 35 | # Run "mix help deps" to learn about dependencies. 36 | defp deps do 37 | [ 38 | {:ex_doc, "~> 0.23", only: :dev, runtime: false}, 39 | {:jason, "~> 1.2", only: :test} 40 | ] 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "earmark_parser": {:hex, :earmark_parser, "1.4.12", "b245e875ec0a311a342320da0551da407d9d2b65d98f7a9597ae078615af3449", [:mix], [], "hexpm", "711e2cc4d64abb7d566d43f54b78f7dc129308a63bc103fbd88550d2174b3160"}, 3 | "ex_doc": {:hex, :ex_doc, "0.23.0", "a069bc9b0bf8efe323ecde8c0d62afc13d308b1fa3d228b65bca5cf8703a529d", [:mix], [{:earmark_parser, "~> 1.4.0", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm", "f5e2c4702468b2fd11b10d39416ddadd2fcdd173ba2a0285ebd92c39827a5a16"}, 4 | "jason": {:hex, :jason, "1.2.2", "ba43e3f2709fd1aa1dce90aaabfd039d000469c05c56f0b8e31978e03fa39052", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "18a228f5f0058ee183f29f9eae0805c6e59d61c3b006760668d8d18ff0d12179"}, 5 | "makeup": {:hex, :makeup, "1.0.5", "d5a830bc42c9800ce07dd97fa94669dfb93d3bf5fcf6ea7a0c67b2e0e4a7f26c", [:mix], [{:nimble_parsec, "~> 0.5 or ~> 1.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "cfa158c02d3f5c0c665d0af11512fed3fba0144cf1aadee0f2ce17747fba2ca9"}, 6 | "makeup_elixir": {:hex, :makeup_elixir, "0.15.1", "b5888c880d17d1cc3e598f05cdb5b5a91b7b17ac4eaf5f297cb697663a1094dd", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.1", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "db68c173234b07ab2a07f645a5acdc117b9f99d69ebf521821d89690ae6c6ec8"}, 7 | "nimble_parsec": {:hex, :nimble_parsec, "1.1.0", "3a6fca1550363552e54c216debb6a9e95bd8d32348938e13de5eda962c0d7f89", [:mix], [], "hexpm", "08eb32d66b706e913ff748f11694b17981c0b04a33ef470e33e11b3d3ac8f54b"}, 8 | } 9 | -------------------------------------------------------------------------------- /test/curvy/key_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Curvy.KeyTest do 2 | use ExUnit.Case, async: true 3 | alias Curvy.Key 4 | 5 | @test_key %Key{ 6 | point: %Curvy.Point{ 7 | x: 4118631015477382459373946646660315625074350024199250279717429272329062331319, 8 | y: 66793862366389912668178571190474290679389778848647827908619288257874616811393 9 | }, 10 | privkey: <<94, 192, 161, 170, 53, 38, 244, 110, 98, 81, 216, 146, 105, 34, 11 | 164, 239, 61, 139, 33, 152, 191, 245, 56, 236, 25, 192, 99, 99, 138, 85, 5, 12 | 185>> 13 | } 14 | 15 | @test_pubkey << 16 | 4, 9, 27, 16, 2, 243, 64, 193, 241, 146, 134, 164, 106, 209, 196, 98, 108, 17 | 104, 106, 24, 91, 35, 36, 119, 126, 92, 179, 246, 227, 179, 30, 51, 183, 147, 18 | 171, 252, 131, 45, 2, 229, 218, 144, 188, 13, 47, 211, 169, 39, 200, 106, 93, 19 | 98, 149, 189, 109, 177, 223, 63, 124, 193, 247, 77, 138, 127, 129>> 20 | @test_pubkey_comp << 21 | 3, 9, 27, 16, 2, 243, 64, 193, 241, 146, 134, 164, 106, 209, 196, 98, 108, 22 | 104, 106, 24, 91, 35, 36, 119, 126, 92, 179, 246, 227, 179, 30, 51, 183>> 23 | 24 | 25 | describe "generate/0" do 26 | test "returns a randomly generated key" do 27 | assert %Key{crv: :secp256k1, point: p, privkey: privkey} = Key.generate() 28 | assert is_integer(p.x) 29 | assert is_integer(p.y) 30 | assert is_binary(privkey) 31 | end 32 | end 33 | 34 | 35 | describe "from_privkey/1" do 36 | test "converts valid privkey into a key pair" do 37 | assert %Key{crv: :secp256k1, point: p} = Key.from_privkey(@test_key.privkey) 38 | assert p.x == @test_key.point.x 39 | assert p.y == @test_key.point.y 40 | end 41 | end 42 | 43 | 44 | describe "from_pubkey/2" do 45 | test "parses valid pubkey binary" do 46 | assert %Key{crv: :secp256k1, point: p} = Key.from_pubkey(@test_pubkey) 47 | assert p.x == @test_key.point.x 48 | assert p.y == @test_key.point.y 49 | end 50 | 51 | test "parses valid compressed pubkey binary" do 52 | assert %Key{crv: :secp256k1, point: p} = Key.from_pubkey(@test_pubkey_comp) 53 | assert p.x == @test_key.point.x 54 | assert p.y == @test_key.point.y 55 | end 56 | end 57 | 58 | 59 | describe "to_privkey/1" do 60 | test "returns privkey binary" do 61 | assert <<_privkey::binary-size(32)>> = Key.to_privkey(@test_key) 62 | end 63 | end 64 | 65 | 66 | describe "to_pubkey/2" do 67 | test "returns pubkey binary with given encoding and compression" do 68 | assert <<_pubkey::binary-size(33)>> = Key.to_pubkey(@test_key) 69 | assert <<_pubkey::binary-size(65)>> = Key.to_pubkey(@test_key, compressed: false) 70 | end 71 | end 72 | 73 | end 74 | -------------------------------------------------------------------------------- /test/curvy/signature_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Curvy.SignatureTest do 2 | use ExUnit.Case, async: true 3 | alias Curvy.Signature 4 | 5 | @test_sig %Signature{ 6 | r: 63173831029936981022572627018246571655303050627048489594159321588908385378810, 7 | s: 4331694221846364448463828256391194279133231453999942381442030409253074198130, 8 | recid: 0 9 | } 10 | 11 | @test_der << 12 | 48, 69, 2, 33, 0, 139, 171, 31, 10, 47, 242, 249, 203, 137, 146, 23, 61, 138, 13 | 215, 60, 34, 157, 49, 234, 142, 16, 176, 244, 212, 174, 26, 13, 142, 215, 96, 14 | 33, 250, 2, 32, 9, 147, 166, 236, 129, 117, 91, 145, 17, 118, 47, 194, 207, 15 | 142, 62, 222, 115, 4, 117, 21, 98, 39, 146, 17, 8, 103, 209, 38, 84, 39, 94, 16 | 114>> 17 | 18 | @test_compact << 19 | 31, 139, 171, 31, 10, 47, 242, 249, 203, 137, 146, 23, 61, 138, 215, 60, 34, 20 | 157, 49, 234, 142, 16, 176, 244, 212, 174, 26, 13, 142, 215, 96, 33, 250, 9, 21 | 147, 166, 236, 129, 117, 91, 145, 17, 118, 47, 194, 207, 142, 62, 222, 115, 4, 22 | 117, 21, 98, 39, 146, 17, 8, 103, 209, 38, 84, 39, 94, 114 23 | >> 24 | 25 | 26 | describe "parse/2" do 27 | test "parses a valid der signature" do 28 | assert %Signature{r: r, s: s, recid: recid} = Signature.parse(@test_der) 29 | assert r == @test_sig.r 30 | assert s == @test_sig.s 31 | assert is_nil(recid) 32 | end 33 | 34 | test "parses a valid compact signature" do 35 | assert %Signature{r: r, s: s, recid: recid} = Signature.parse(@test_compact) 36 | assert r == @test_sig.r 37 | assert s == @test_sig.s 38 | assert recid == 0 39 | end 40 | end 41 | 42 | 43 | describe "to_der/1" do 44 | test "returns der encoded signature" do 45 | assert Signature.to_der(@test_sig) == @test_der 46 | end 47 | end 48 | 49 | 50 | describe "to_compact/1" do 51 | test "returns compact signature" do 52 | assert Signature.to_compact(@test_sig) == @test_compact 53 | end 54 | 55 | test "returns compact signature with correct prefix" do 56 | assert <<32, _::binary>> = Signature.to_compact(@test_sig, recovery_id: 1) 57 | assert <<33, _::binary>> = Signature.to_compact(@test_sig, recovery_id: 2) 58 | assert <<34, _::binary>> = Signature.to_compact(@test_sig, recovery_id: 3) 59 | end 60 | 61 | test "returns compact signature with correct prefix for uncompressed" do 62 | assert <<28, _::binary>> = Signature.to_compact(@test_sig, recovery_id: 1, compressed: false) 63 | assert <<29, _::binary>> = Signature.to_compact(@test_sig, recovery_id: 2, compressed: false) 64 | assert <<30, _::binary>> = Signature.to_compact(@test_sig, recovery_id: 3, compressed: false) 65 | end 66 | 67 | test "raises error if not a valid recovery ID" do 68 | assert_raise RuntimeError, "Recovery ID not in range 0..3", fn -> @test_sig |> Map.put(:recid, nil) |> Signature.to_compact() end 69 | assert_raise RuntimeError, "Recovery ID not in range 0..3", fn -> Signature.to_compact(@test_sig, recovery_id: -1) end 70 | assert_raise RuntimeError, "Recovery ID not in range 0..3", fn -> Signature.to_compact(@test_sig, recovery_id: 4) end 71 | end 72 | end 73 | 74 | end 75 | -------------------------------------------------------------------------------- /test/curvy/vector_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Curvy.VectorTest do 2 | use ExUnit.Case, async: true 3 | 4 | @rfc6979_vectors File.read!("test/vectors/ecdsa.json") 5 | |> Jason.decode!() 6 | 7 | @ecdh_vectors File.read!("test/vectors/ecdh.json") 8 | |> Jason.decode!() 9 | |> Map.get("testGroups") 10 | |> List.first() 11 | |> Map.get("tests") 12 | 13 | @ecdh_valid Enum.filter(@ecdh_vectors, & &1["result"] == "valid") 14 | 15 | describe "Curvy.sign/3 rfc6979 vectors" do 16 | for {vector, i} <- Enum.with_index(@rfc6979_vectors["valid"]) do 17 | test "passes valid vector: #{i}" do 18 | %{"m" => m, "d" => d, "signature" => sig} = unquote(Macro.escape(vector)) 19 | <<_prefix, res::binary>> = Curvy.sign(Base.decode16!(m, case: :lower), Base.decode16!(d, case: :lower), hash: false, compact: true) 20 | assert res == Base.decode16!(sig, case: :lower) 21 | end 22 | end 23 | end 24 | 25 | describe "Curvy.get_shared_secret/3 test vectors" do 26 | for {vector, i} <- Enum.with_index(@ecdh_valid) do 27 | test "passes valid vector: #{i}" do 28 | v = unquote(Macro.escape(vector)) 29 | privkey = v["private"] |> Base.decode16!(case: :lower) |> ecdh_privkey() 30 | pubkey = v["public"] |> Base.decode16!(case: :lower) |> ecdh_pubkey() 31 | assert Curvy.get_shared_secret(privkey, pubkey, encoding: :hex) == v["shared"] 32 | end 33 | end 34 | end 35 | 36 | def ecdh_privkey(<<_prefix, privkey::binary-size(32)>>), do: privkey 37 | 38 | def ecdh_privkey(privkey) do 39 | :binary.copy(<<0>>, 32-byte_size(privkey)) 40 | |> Kernel.<>(privkey) 41 | end 42 | 43 | def ecdh_pubkey(<<_der::binary-size(23), pubkey::binary>>), do: pubkey 44 | 45 | end 46 | -------------------------------------------------------------------------------- /test/curvy_test.exs: -------------------------------------------------------------------------------- 1 | defmodule CurvyTest do 2 | use ExUnit.Case, async: true 3 | alias Curvy.Key 4 | 5 | @test_key %Key{ 6 | point: %Curvy.Point{ 7 | x: 4118631015477382459373946646660315625074350024199250279717429272329062331319, 8 | y: 66793862366389912668178571190474290679389778848647827908619288257874616811393 9 | }, 10 | privkey: <<94, 192, 161, 170, 53, 38, 244, 110, 98, 81, 216, 146, 105, 34, 11 | 164, 239, 61, 139, 33, 152, 191, 245, 56, 236, 25, 192, 99, 99, 138, 85, 5, 12 | 185>> 13 | } 14 | 15 | @test_key_2 %Key{ 16 | point: %Curvy.Point{ 17 | x: 18104471324754606025397722809760948127956696160058047068016426305179077487064, 18 | y: 29609997689294885043479429890515147582121499892730909103923743804350436693119 19 | }, 20 | privkey: <<65, 20, 145, 128, 181, 91, 11, 5, 227, 139, 223, 209, 143, 155, 21 | 170, 148, 115, 249, 64, 53, 140, 70, 50, 140, 125, 196, 66, 64, 203, 189, 22 | 172, 1>> 23 | } 24 | 25 | 26 | describe "generate_key/0" do 27 | test "returns a randomly generated key" do 28 | assert %Key{} = Curvy.generate_key() 29 | end 30 | end 31 | 32 | 33 | @test_secret << 34 | 241, 47, 119, 25, 77, 84, 86, 10, 220, 16, 169, 64, 156, 169, 122, 143, 210, 35 | 62, 226, 204, 143, 254, 197, 249, 125, 57, 216, 15, 205, 25, 170, 217>> 36 | @test_secret_b64 "8S93GU1UVgrcEKlAnKl6j9I+4syP/sX5fTnYD80Zqtk=" 37 | @test_secret_hex "f12f77194d54560adc10a9409ca97a8fd23ee2cc8ffec5f97d39d80fcd19aad9" 38 | 39 | describe "get_shared_secret/3" do 40 | test "returns a shared secret in the given encoding" do 41 | assert Curvy.get_shared_secret(@test_key, @test_key_2) == @test_secret 42 | assert Curvy.get_shared_secret(@test_key, @test_key_2, encoding: :base64) == @test_secret_b64 43 | assert Curvy.get_shared_secret(@test_key, @test_key_2, encoding: :hex) == @test_secret_hex 44 | end 45 | 46 | test "returns same result in reverse" do 47 | assert Curvy.get_shared_secret(@test_key_2, @test_key) == @test_secret 48 | end 49 | 50 | test "constent with built in erlang results" do 51 | assert :crypto.compute_key(:ecdh, Key.to_pubkey(@test_key_2), @test_key.privkey, :secp256k1) == @test_secret 52 | assert :crypto.compute_key(:ecdh, Key.to_pubkey(@test_key), @test_key_2.privkey, :secp256k1) == @test_secret 53 | end 54 | 55 | test "accepts binary keys" do 56 | assert Curvy.get_shared_secret(Key.to_privkey(@test_key), Key.to_pubkey(@test_key_2)) == @test_secret 57 | end 58 | end 59 | 60 | 61 | describe "recover_key/3" do 62 | test "recovers from a der sig if you have the recovery id" do 63 | {sig, recovery_id} = Curvy.sign("testing recovery", @test_key, recovery: true) 64 | assert %Key{point: point} = Curvy.recover_key(sig, "testing recovery", recovery_id: recovery_id) 65 | assert point == @test_key.point 66 | end 67 | 68 | test "recovers from a compact sig automatically" do 69 | sig = Curvy.sign("testing recovery", @test_key, compact: true) 70 | assert %Key{point: point} = Curvy.recover_key(sig, "testing recovery") 71 | assert point == @test_key.point 72 | end 73 | 74 | test "correctly recovers uncompressed keys" do 75 | test_key = Map.put(@test_key, :compressed, false) 76 | sig = Curvy.sign("testing recovery", test_key, compact: true) 77 | assert %Key{point: point, compressed: false} = Curvy.recover_key(sig, "testing recovery") 78 | assert point == @test_key.point 79 | end 80 | 81 | test "raises error if not a valid recovery ID" do 82 | assert_raise RuntimeError, "Recovery ID not in range 0..3", fn -> 83 | Curvy.sign("testing recovery", @test_key) |> Curvy.recover_key("testing recovery") 84 | end 85 | end 86 | end 87 | 88 | 89 | @test_sig << 90 | 48, 68, 2, 32, 42, 65, 162, 214, 121, 255, 204, 204, 227, 137, 211, 178, 122, 91 | 128, 172, 232, 164, 118, 53, 56, 153, 4, 174, 102, 112, 28, 162, 64, 44, 60, 92 | 213, 100, 2, 32, 49, 19, 136, 160, 56, 233, 56, 176, 40, 4, 227, 47, 135, 81, 93 | 79, 233, 233, 93, 249, 146, 2, 116, 213, 39, 183, 242, 72, 188, 44, 66, 115, 94 | 60>> 95 | @test_sig_b64 "MEQCICpBotZ5/8zM44nTsnqArOikdjU4mQSuZnAcokAsPNVkAiAxE4igOOk4sCgE4y+HUU/p6V35kgJ01Se38ki8LEJzPA==" 96 | @test_sig_hex "304402202a41a2d679ffcccce389d3b27a80ace8a47635389904ae66701ca2402c3cd5640220311388a038e938b02804e32f87514fe9e95df9920274d527b7f248bc2c42733c" 97 | 98 | @test_sig_c << 99 | 32, 42, 65, 162, 214, 121, 255, 204, 204, 227, 137, 211, 178, 122, 128, 172, 100 | 232, 164, 118, 53, 56, 153, 4, 174, 102, 112, 28, 162, 64, 44, 60, 213, 100, 101 | 49, 19, 136, 160, 56, 233, 56, 176, 40, 4, 227, 47, 135, 81, 79, 233, 233, 93, 102 | 249, 146, 2, 116, 213, 39, 183, 242, 72, 188, 44, 66, 115, 60>> 103 | @test_sig_c_b64 "ICpBotZ5/8zM44nTsnqArOikdjU4mQSuZnAcokAsPNVkMROIoDjpOLAoBOMvh1FP6eld+ZICdNUnt/JIvCxCczw=" 104 | @test_sig_c_hex "202a41a2d679ffcccce389d3b27a80ace8a47635389904ae66701ca2402c3cd564311388a038e938b02804e32f87514fe9e95df9920274d527b7f248bc2c42733c" 105 | 106 | describe "sign/3" do 107 | test "signs a message with the given encoding" do 108 | assert Curvy.sign("hello", @test_key) == @test_sig 109 | assert Curvy.sign("hello", @test_key, encoding: :base64) == @test_sig_b64 110 | assert Curvy.sign("hello", @test_key, encoding: :hex) == @test_sig_hex 111 | end 112 | 113 | test "signs a compact message with the given encoding" do 114 | assert Curvy.sign("hello", @test_key, compact: true) == @test_sig_c 115 | assert Curvy.sign("hello", @test_key, compact: true, encoding: :base64) == @test_sig_c_b64 116 | assert Curvy.sign("hello", @test_key, compact: true, encoding: :hex) == @test_sig_c_hex 117 | end 118 | 119 | test "returns signature with recovery id" do 120 | assert {sig, recovery_id} = Curvy.sign("hello", @test_key, recovery: true) 121 | assert sig == @test_sig 122 | assert is_integer(recovery_id) 123 | end 124 | 125 | test "signs a message without hash digest" do 126 | refute Curvy.sign("hello", @test_key, hash: false) == @test_sig 127 | end 128 | 129 | test "signs a message without low s normalization" do 130 | refute Curvy.sign("hello", @test_key, normalize: false) == @test_sig 131 | end 132 | 133 | test "verifyable with built in erlang crypto" do 134 | assert :crypto.verify(:ecdsa, :sha256, "hello", @test_sig, [Key.to_pubkey(@test_key), :secp256k1]) 135 | assert :crypto.verify(:ecdsa, :sha256, "hello", Curvy.sign("hello", @test_key, normalize: false), [Key.to_pubkey(@test_key), :secp256k1]) 136 | end 137 | end 138 | 139 | describe "verify/4" do 140 | test "verifies signatures with the given encoding" do 141 | assert Curvy.verify(@test_sig, "hello", @test_key) 142 | assert Curvy.verify(@test_sig_b64, "hello", @test_key, encoding: :base64) 143 | assert Curvy.verify(@test_sig_hex, "hello", @test_key, encoding: :hex) 144 | end 145 | 146 | test "verifies compact signatures with the given encoding" do 147 | assert Curvy.verify(@test_sig_c, "hello", @test_key) 148 | assert Curvy.verify(@test_sig_c_b64, "hello", @test_key, encoding: :base64) 149 | assert Curvy.verify(@test_sig_c_hex, "hello", @test_key, encoding: :hex) 150 | end 151 | 152 | test "verifies a message without hash digest" do 153 | Curvy.sign("hello", @test_key, hash: false) 154 | |> Curvy.verify("hello", @test_key, hash: false) 155 | |> assert 156 | end 157 | 158 | test "verifies a message without low s normalization" do 159 | Curvy.sign("hello", @test_key, normalize: false) 160 | |> Curvy.verify("hello", @test_key) 161 | |> assert 162 | end 163 | 164 | test "wont verify if message incorrect" do 165 | refute Curvy.verify(@test_sig, "wrong", @test_key) 166 | end 167 | 168 | test "wont verify if key incorrect" do 169 | refute Curvy.verify(@test_sig, "hello", @test_key_2) 170 | end 171 | 172 | test "wont verify if hash algo incorrect" do 173 | refute Curvy.verify(@test_sig, "hello", @test_key, hash: false) 174 | end 175 | 176 | test "returns error if signature is garbage" do 177 | assert :error = Curvy.verify(:crypto.strong_rand_bytes(32), "hello", @test_key) 178 | end 179 | 180 | test "returns error if signature decoding error" do 181 | assert :error = Curvy.verify(@test_sig_b64, "hello", @test_key, encoding: :hex) 182 | end 183 | end 184 | end 185 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------