h2c 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9bb9442ab449a3426c342b352746b7057a4d6bb15b3d88efdaf214a0e7e11423
4
+ data.tar.gz: 19c35110d60cf84cfc221c33a9ae4f8ff612ae8ac532a25512e9cd66bc8fcb0a
5
+ SHA512:
6
+ metadata.gz: 61fd4f3cff6441eaf34e3b7507ee6fd67fe158f3622f1e42a69c44c8bbb950385fb61439b3bbc88523a23c81b4369405728eade93319b28fbb889532ee99f125
7
+ data.tar.gz: '049c98d23b13a876a37ec2a8f13aa8a6449a43a2a0f869b7a31e7d702503850a406aa7ddb86fe65922d742dd1287b7b4b1a71cf395afc3041d95aadc51924084'
data/.prettierignore ADDED
@@ -0,0 +1,2 @@
1
+ /bin
2
+ /vendor
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,21 @@
1
+ require:
2
+ - rubocop-rake
3
+ - rubocop-rspec
4
+ inherit_gem:
5
+ prettier: rubocop.yml
6
+ AllCops:
7
+ TargetRubyVersion: 2.7
8
+ RSpec/ExampleLength:
9
+ Enabled: false
10
+ Metrics:
11
+ Enabled: false
12
+ RSpec/MultipleExpectations:
13
+ Max: 5
14
+ Style/IfUnlessModifier:
15
+ Enabled: false
16
+ Style/WhileUntilModifier:
17
+ Enabled: false
18
+ Naming/MethodParameterName:
19
+ Enabled: false
20
+ RSpec/FilePath:
21
+ Enabled: false
data/.ruby-gemset ADDED
@@ -0,0 +1 @@
1
+ h2c
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ ruby-3.2.0
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-12-26
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at azuchi@chaintope.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in h2c.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem 'prettier'
13
+
14
+ gem 'rubocop-rake'
15
+ gem 'rubocop-rspec'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 azuchi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # Hashing to Elliptic Curves for Ruby
2
+
3
+ This is a Ruby implementation of the [Hash to Curves](https://github.com/cfrg/draft-irtf-cfrg-hash-to-curve) proposed by the [IETF](https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/).
4
+
5
+ It has been tested using the Test Vector provided, but the code has not been audited to ensure functional specification and safety. Also It is under development and is subject to change without backward compatibility.
6
+
7
+ The following cipher suites are currently supported:
8
+
9
+ * secp256k1_XMD:SHA-256_SSWU_NU_
10
+ * secp256k1_XMD:SHA-256_SSWU_RO_
11
+
12
+ ## Installation
13
+
14
+ Add this line to your application's Gemfile:
15
+
16
+ ```ruby
17
+ gem 'h2c'
18
+ ```
19
+
20
+ And then execute:
21
+
22
+ $ bundle install
23
+
24
+ Or install it yourself as:
25
+
26
+ $ gem install h2c
27
+
28
+ ## Usage
29
+
30
+ ```ruby
31
+ require 'h2c'
32
+
33
+ sutie = "secp256k1_XMD:SHA-256_SSWU_RO_"
34
+ dst = "QUUX-V01-CS02-with-secp256k1_XMD:SHA-256_SSWU_RO_"
35
+
36
+ h2c = H2C.get(sutie, dst)
37
+
38
+ msg = "abc"
39
+
40
+ result = h2c.digest(msg)
41
+ puts result.inspect
42
+ #<ECDSA::Point: secp256k1, 0x3377e01eab42db296b512293120c6cee72b6ecf9f9205760bd9ff11fb3cb2c4b, 0x7f95890f33efebd1044d382a01b1bee0900fb6116f94688d487c6c7b9c8371f6>
43
+ ```
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "h2c"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/h2c.gemspec ADDED
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/h2c/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "h2c"
7
+ spec.version = H2C::VERSION
8
+ spec.authors = ["azuchi"]
9
+ spec.email = ["azuchi@chaintope.com"]
10
+
11
+ spec.summary = "Ruby implementation of hash to curve."
12
+ spec.description = "Ruby implementation of hash to curve."
13
+ spec.homepage = "https://github.com/azuchi/h2c"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.7.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = spec.homepage
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
26
+ end
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ # Uncomment to register a new dependency of your gem
33
+ # spec.add_dependency "example-gem", "~> 1.0"
34
+ spec.add_dependency "ecdsa", "~> 1.2.0"
35
+
36
+ # For more information and examples about making a new gem, check out our
37
+ # guide at: https://bundler.io/guides/creating_gem.html
38
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+ module ECDSA
3
+ class Group
4
+ Secp256k1_3ISO =
5
+ new(
6
+ name: "secp256k1_3ISO",
7
+ p:
8
+ 0xFFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFE_FFFFFC2F,
9
+ a: 0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533,
10
+ b: 1771,
11
+ g: [
12
+ 0xa677f67dec3b4e958267664f4bead0c300959b89cdfae2fbb7563af10a26088a,
13
+ 0xb683b56744d1140cbda41b9853bb2fb7cc44b06dc61406db73c387aea4e680d3
14
+ ],
15
+ n:
16
+ 0xFFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFE_BAAEDCE6_AF48A03B_BFD25E8C_D0364141,
17
+ h: 1
18
+ )
19
+ end
20
+ end
data/lib/ext/curve.rb ADDED
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "curve/secp256k1_3iso"
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+ require "digest"
3
+
4
+ module H2C
5
+ module Expander
6
+ # Expander::XML produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
7
+ class XMD
8
+ attr_reader :dst, :digest
9
+ # Constructor
10
+ # @param [String] func Hash function name. Currently supported by 'SHA256' and 'SHA512'
11
+ # @param [String] dst Domain separation tag with binary format.
12
+ # @raise [H2C::Error] If invalid func specified.
13
+ def initialize(func, dst)
14
+ @dst = dst
15
+ @digest =
16
+ case func
17
+ when HashFunc::SHA256
18
+ Digest(HashFunc::SHA256).new
19
+ when HashFunc::SHA512
20
+ Digest(HashFunc::SHA512).new
21
+ else
22
+ raise H2C::Error, "func #{func} is unsupported."
23
+ end
24
+ end
25
+
26
+ # Expand message.
27
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-expand_message_xmd
28
+ # @param [String] msg The message to be expanded with binary format.
29
+ # @param [Integer] len The length of the requested output in bytes.
30
+ # @return [String] Expanded message.
31
+ # @raise [H2C::Error]
32
+ def expand(msg, len)
33
+ b_len = digest.digest_length
34
+ ell = (len + b_len - 1) / b_len
35
+ dst_prime = construct_dst_prime
36
+
37
+ if ell >= 0xff || len >= 0xffff || dst_prime.bytesize >= 0xff
38
+ raise H2C::Error, "requested too many bytes"
39
+ end
40
+ lib_str = [(len >> 8) & 0xFF, (len & 0xff)].pack("CC")
41
+ z_pad = Array.new(digest.block_length, 0)
42
+
43
+ digest.reset
44
+ digest.update(z_pad.pack("C*"))
45
+ digest.update(msg)
46
+ digest.update(lib_str)
47
+ digest.update([0].pack("C"))
48
+ digest.update(dst_prime)
49
+
50
+ b0 = digest.digest
51
+ digest.reset
52
+ digest.update(b0)
53
+ digest.update([1].pack("C"))
54
+ digest.update(dst_prime)
55
+
56
+ bi = digest.digest
57
+ pseudo = bi
58
+ (2..(ell + 1)).each do |i|
59
+ digest.reset
60
+ digest.update(Expander.xor(b0, bi))
61
+ digest.update([i].pack("C"))
62
+ digest.update(dst_prime)
63
+ bi = digest.digest
64
+ pseudo += bi
65
+ end
66
+ pseudo[0...len]
67
+ end
68
+
69
+ # Construct DST prime.
70
+ # @return [String] DST prime
71
+ def construct_dst_prime
72
+ dst_prime =
73
+ if dst.bytesize > MAX_DST_LENGTH
74
+ digest.digest(LONG_DST_PREFIX + dst)
75
+ else
76
+ dst
77
+ end
78
+ dst_prime + [dst_prime.bytesize].pack("C")
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module H2C
4
+ # Expander allows to generate a pseudo-random byte string of a determined length.
5
+ module Expander
6
+ autoload :XMD, "h2c/expander/xmd"
7
+
8
+ # Maximum allowed length for domain separation tags.
9
+ MAX_DST_LENGTH = 255
10
+
11
+ LONG_DST_PREFIX = [
12
+ 0x48,
13
+ 0x32,
14
+ 0x43,
15
+ 0x2d,
16
+ 0x4f,
17
+ 0x56,
18
+ 0x45,
19
+ 0x52,
20
+ 0x53,
21
+ 0x49,
22
+ 0x5a,
23
+ 0x45,
24
+ 0x2d,
25
+ 0x44,
26
+ 0x53,
27
+ 0x54,
28
+ 0x2d
29
+ ].pack("C*")
30
+
31
+ module_function
32
+
33
+ # Get expander implementation
34
+ # @param [String] func Hash function name. Currently supported by 'SHA-256' and 'SHA-512'.
35
+ # @raise [H2C::Error] If invalid func specified.
36
+ def get(func, dst, _k)
37
+ unless HashFunc::XMD_FUNCS.include?(func)
38
+ raise H2C::Error, "func #{func} is unsupported."
39
+ end
40
+ XMD.new(func, dst)
41
+ # TODO: XOR
42
+ end
43
+
44
+ # XOR two byte(+x+ and +y+) string.
45
+ # @param [String] x byte strings
46
+ # @param [String] y byte strings
47
+ # @return [String] xored byte strings
48
+ def xor(x, y)
49
+ x_bytes = x.unpack("C*")
50
+ y_bytes = y.unpack("C*")
51
+ x_bytes.zip(y_bytes).map { |a, b| a ^ b }.pack("C*")
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module H2C
4
+ # Complete and secure function for hashing strings to points.
5
+ class HashToPoint
6
+ attr_reader :suite
7
+
8
+ # @param [H2C::Suite] suite Hash to curve suite
9
+ def initialize(suite)
10
+ @suite = suite
11
+ end
12
+
13
+ # Hash returns a point on an elliptic curve given a message.
14
+ # @param [String] msg Message with binary to be hashed.
15
+ # @return [ECDSA::Point] point
16
+ def digest(msg)
17
+ if suite.ro
18
+ u = hash_to_field(msg, 2)
19
+ p0 = suite.map.map(u[0])
20
+ p1 = suite.map.map(u[1])
21
+ p0 + p1
22
+ else
23
+ u = hash_to_field(msg, 1)
24
+ suite.map.map(u[0])
25
+ end
26
+ end
27
+
28
+ # Hashes a msg of any length into an element of a finite field.
29
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-hash_to_field-implementatio
30
+ # @param [String] msg A byte string containing the message to hash.
31
+ # @param [Integer] count The number of elements of Field to output.
32
+ # @return [Array]
33
+ def hash_to_field(msg, count)
34
+ field = suite.curve.field
35
+ len = count * suite.m * suite.l
36
+ pseudo = suite.exp.expand(msg, len)
37
+ u = []
38
+ (0...count).each do |i|
39
+ v = []
40
+ (0...suite.m).each do |j|
41
+ offset = suite.l * (j + i * suite.m)
42
+ t = pseudo[offset, (offset + suite.l)]
43
+ vj = t.unpack1("H*").to_i(16)
44
+ v[j] = field.mod(vj)
45
+ end
46
+ u[i] = v
47
+ end
48
+ u.flatten
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+ module H2C
3
+ module M2C
4
+ module ISOGeny
5
+ # 3-isogeny map for secp256k1
6
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#appendix-E.1
7
+ class Secp256k1
8
+ attr_reader :e0, :e1
9
+
10
+ X_NUM = [
11
+ 0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7,
12
+ 0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581,
13
+ 0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262,
14
+ 0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c
15
+ ].freeze
16
+ X_DEN = [
17
+ 0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b,
18
+ 0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14,
19
+ 1,
20
+ 0
21
+ ].freeze
22
+ Y_NUM = [
23
+ 0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c,
24
+ 0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3,
25
+ 0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931,
26
+ 0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84
27
+ ].freeze
28
+ Y_DEN = [
29
+ 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b,
30
+ 0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573,
31
+ 0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f,
32
+ 1
33
+ ].freeze
34
+
35
+ def initialize
36
+ @e0 = ECDSA::Group::Secp256k1_3ISO
37
+ @e1 = ECDSA::Group::Secp256k1
38
+ end
39
+
40
+ def map(x, y)
41
+ f = e0.field
42
+
43
+ x_num = 0
44
+ x_den = 0
45
+ y_num = 0
46
+ y_den = 0
47
+ 3.step(0, -1) do |i|
48
+ x_num = f.mod(x_num * x + X_NUM[i])
49
+ x_den = f.mod(x_den * x + X_DEN[i])
50
+ y_num = f.mod(y_num * x + Y_NUM[i])
51
+ y_den = f.mod(y_den * x + Y_DEN[i])
52
+ end
53
+ xx = f.mod(x_num * f.inverse(x_den))
54
+ yy = f.mod(y * (y_num * f.inverse(y_den)))
55
+ [xx, yy]
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+ module H2C
3
+ module M2C
4
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-isogeny-maps-for-suites
5
+ module ISOGeny
6
+ autoload :Secp256k1, "h2c/m2c/isogeny/secp256k1"
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module H2C
4
+ module M2C
5
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#section-6.6.2
6
+ class SSWU
7
+ attr_reader :curve, :c1, :c2, :z
8
+
9
+ # Constructor
10
+ # @param [ECDSA::Group] curve
11
+ # @param [Integer] z
12
+ def initialize(curve, z)
13
+ @curve = curve
14
+ @z = z
15
+ f = curve.field
16
+ @c1 = f.mod(-curve.param_b * f.inverse(curve.param_a))
17
+ @c2 = f.mod(-f.inverse(z))
18
+ end
19
+
20
+ # Outputs x and y are elements of the field F.
21
+ # @param [Integer] u
22
+ # @return [Array(Integer, Integer)] x and y
23
+ def map(u)
24
+ f = curve.field
25
+ t1 = f.mod(f.power(u, 2) * f.mod(z))
26
+ t2 = f.power(t1, 2)
27
+ x1 = f.mod(t1 + t2)
28
+ x1 = f.inverse(x1)
29
+ e1 = x1.zero?
30
+ x1 = f.mod(x1 + 1)
31
+ x1 = e1 ? c2 : x1
32
+ x1 = f.mod(x1 * c1)
33
+ gx1 = f.power(x1, 2)
34
+ gx1 = f.mod(gx1 + curve.param_a)
35
+ gx1 = f.mod(gx1 * x1)
36
+ gx1 = f.mod(gx1 + curve.param_b)
37
+ x2 = f.mod(t1 * x1)
38
+ t2 = f.mod(t1 * t2)
39
+ gx2 = f.mod(gx1 * t2)
40
+ e2 = square?(gx1)
41
+ x = e2 ? x1 : x2
42
+ y2 = e2 ? gx1 : gx2
43
+ y = f.square_roots(y2)[0]
44
+ e3 = sgn0(u) == sgn0(y)
45
+ y = f.mod(e3 ? y : -y)
46
+ [x, y]
47
+ end
48
+
49
+ def square?(x)
50
+ test = curve.field.power(x, ((curve.field.prime - 1) / 2))
51
+ [0, 1].include?(test)
52
+ end
53
+
54
+ def sgn0(x)
55
+ res = x % 2
56
+ curve.field.mod(1 - 2 * res)
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+ module H2C
3
+ module M2C
4
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#section-6.6.3
5
+ class SSWUAB0
6
+ attr_reader :sswu, :iso
7
+
8
+ # Constructor
9
+ # @param [H2C::M2C::ISOGeny] iso
10
+ # @param [Integer] z
11
+ def initialize(iso, z)
12
+ @sswu = SSWU.new(iso.e0, z)
13
+ @iso = iso
14
+ end
15
+
16
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#section-6.6.3
17
+ # @param [Integer] u
18
+ # @return [ECDSA::Point]
19
+ def map(u)
20
+ x, y = sswu.map(u)
21
+ coordinate = iso.map(x, y)
22
+ iso.e1.new_point(coordinate)
23
+ end
24
+ end
25
+ end
26
+ end
data/lib/h2c/m2c.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module H2C
4
+ # Map to Curve functions.
5
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#section-6
6
+ module M2C
7
+ autoload :ISOGeny, "h2c/m2c/isogeny"
8
+ autoload :SSWU, "h2c/m2c/sswu"
9
+ autoload :SSWUAB0, "h2c/m2c/sswuab0"
10
+ end
11
+ end
data/lib/h2c/suite.rb ADDED
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+ module H2C
3
+ # Hash to curve suites
4
+ class Suite
5
+ attr_reader :id, :curve, :k, :exp, :m, :l, :ro, :map
6
+
7
+ SECP256K1_XMDSHA256_SSWU_NU_ = "secp256k1_XMD:SHA-256_SSWU_NU_"
8
+ SECP256K1_XMDSHA256_SSWU_RO_ = "secp256k1_XMD:SHA-256_SSWU_RO_"
9
+
10
+ # Initialize suite
11
+ # @param [String] id Suite id.
12
+ # @param [String] dst Domain separation tag.
13
+ def initialize(id, dst)
14
+ @id = id
15
+ case id
16
+ when SECP256K1_XMDSHA256_SSWU_NU_, SECP256K1_XMDSHA256_SSWU_RO_
17
+ @curve = ECDSA::Group::Secp256k1
18
+ @k = 128
19
+ @exp = Expander.get(HashFunc::SHA256, dst, @k)
20
+ @m = 1
21
+ @l = 48
22
+ @map = M2C::SSWUAB0.new(H2C::M2C::ISOGeny::Secp256k1.new, -11)
23
+ @ro = (id == SECP256K1_XMDSHA256_SSWU_RO_)
24
+ else
25
+ raise H2C::Error, "suite #{curve} unsupported."
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module H2C
4
+ VERSION = "0.1.0"
5
+ end
data/lib/h2c.rb ADDED
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "h2c/version"
4
+ require "ecdsa"
5
+ require_relative "ext/curve"
6
+
7
+ # Hash to Curves library.
8
+ # https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html
9
+ module H2C
10
+ class Error < StandardError
11
+ end
12
+
13
+ autoload :Expander, "h2c/expander"
14
+ autoload :Suite, "h2c/suite"
15
+ autoload :HashToPoint, "h2c/hash_to_point"
16
+ autoload :M2C, "h2c/m2c"
17
+
18
+ # Hash function name
19
+ module HashFunc
20
+ SHA256 = "SHA256"
21
+ SHA512 = "SHA512"
22
+ SHAKE128 = "SHAKE128"
23
+ SHAKE256 = "SHAKE256"
24
+
25
+ XMD_FUNCS = [SHA256, SHA512].freeze
26
+ XOF_FUNCS = [SHAKE128, SHAKE256].freeze
27
+ end
28
+
29
+ module_function
30
+
31
+ # Get hash to curve corresponding to +suite+.
32
+ #
33
+ # @param [String] suite Suite name for hashing.
34
+ # Currently supported are "secp256k1_XMD:SHA-256_SSWU_NU_" and "secp256k1_XMD:SHA-256_SSWU_RO_".
35
+ # @param [String] dst Domain separation tag.
36
+ # @return [H2C::HashToPoint]
37
+ def get(suite, dst)
38
+ suite = Suite.new(suite, dst)
39
+ HashToPoint.new(suite)
40
+ end
41
+ end
data/sig/h2c.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module H2C
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,88 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: h2c
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - azuchi
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-01-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ecdsa
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 1.2.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 1.2.0
27
+ description: Ruby implementation of hash to curve.
28
+ email:
29
+ - azuchi@chaintope.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".prettierignore"
35
+ - ".rspec"
36
+ - ".rubocop.yml"
37
+ - ".ruby-gemset"
38
+ - ".ruby-version"
39
+ - CHANGELOG.md
40
+ - CODE_OF_CONDUCT.md
41
+ - Gemfile
42
+ - LICENSE.txt
43
+ - README.md
44
+ - Rakefile
45
+ - bin/console
46
+ - bin/setup
47
+ - h2c.gemspec
48
+ - lib/ext/curve.rb
49
+ - lib/ext/curve/secp256k1_3iso.rb
50
+ - lib/h2c.rb
51
+ - lib/h2c/expander.rb
52
+ - lib/h2c/expander/xmd.rb
53
+ - lib/h2c/hash_to_point.rb
54
+ - lib/h2c/m2c.rb
55
+ - lib/h2c/m2c/isogeny.rb
56
+ - lib/h2c/m2c/isogeny/secp256k1.rb
57
+ - lib/h2c/m2c/sswu.rb
58
+ - lib/h2c/m2c/sswuab0.rb
59
+ - lib/h2c/suite.rb
60
+ - lib/h2c/version.rb
61
+ - sig/h2c.rbs
62
+ homepage: https://github.com/azuchi/h2c
63
+ licenses:
64
+ - MIT
65
+ metadata:
66
+ homepage_uri: https://github.com/azuchi/h2c
67
+ source_code_uri: https://github.com/azuchi/h2c
68
+ changelog_uri: https://github.com/azuchi/h2c
69
+ post_install_message:
70
+ rdoc_options: []
71
+ require_paths:
72
+ - lib
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: 2.7.0
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ requirements: []
84
+ rubygems_version: 3.4.1
85
+ signing_key:
86
+ specification_version: 4
87
+ summary: Ruby implementation of hash to curve.
88
+ test_files: []