Class: Scl::SecretShare
- Inherits:
-
Object
- Object
- Scl::SecretShare
- Defined in:
- lib/scl/secret_share.rb
Class Method Summary collapse
Instance Method Summary collapse
- #generate(secret) ⇒ Object
-
#initialize(minimum, shares, encoder: Format::BASE64) ⇒ SecretShare
constructor
A new instance of SecretShare.
Constructor Details
#initialize(minimum, shares, encoder: Format::BASE64) ⇒ SecretShare
Returns a new instance of SecretShare.
9 10 11 12 13 14 |
# File 'lib/scl/secret_share.rb', line 9 def initialize(minimum, shares, encoder: Format::BASE64) raise "Minimum must be larger than zero and less than shares" unless (0..shares) === minimum @encoder = encoder @minimum = minimum @shares = shares end |
Class Method Details
.combine(shares, encoder: nil) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/scl/secret_share.rb', line 35 def self.combine(shares, encoder: nil) decoded = shares.map do |share| share = encoder && encoder != Format::BASE64 ? encoder.decode(share) : share share.chars.each_slice(ENCODED_CHUNK_SIZE).map(&:join).each_slice(2).map do |random, polynomial| OpenStruct.new({ x: base64_decode(random), y: base64_decode(polynomial) }) end end chunks = decoded[0].length.times.map do |chunk| secret = OpenSSL::BN.new(0) decoded.each do |share| point = share[chunk] numerator, denominator = OpenSSL::BN.new(1), OpenSSL::BN.new(1) decoded.each do |peer| if peer != share current = peer[chunk].x numerator = OpenSSL::BN.new((numerator * -current).to_i % PRIME) denominator = OpenSSL::BN.new((denominator * (point.x - current)).to_i % PRIME) end end working = (point.y * numerator) * mod_inverse(denominator) + PRIME secret = ((secret + working) + 1000 * PRIME) % PRIME end secret end hex_data = chunks.map{|chunk| chunk.to_s(16).rjust(64, "0") }.join hex_data.chars.each_slice(64).map(&:join).map do |chunk| chunk.gsub(/(?:00)+$/,'').chars.each_slice(2).map{|pair| pair.join.to_i(16).chr } end.join end |
Instance Method Details
#generate(secret) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/scl/secret_share.rb', line 16 def generate(secret) polynomials = chunks(secret).map do |chunk| [chunk] + (@minimum - 1).times.map do |i| random end end @shares.times.map do |i| result = '' polynomials.map do |polynomial| x = random y = evaluate_polynomial(polynomial, x) result << base64_encode(x) result << base64_encode(y) end @encoder == Format::BASE64 ? result : @encoder.encode(result) end end |