Class: Sodium::Sign

Inherits:
Object
  • Object
show all
Includes:
Delegate
Defined in:
lib/sodium/sign.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Delegate

class_methods, included, #primitive

Constructor Details

#initialize(key) ⇒ Sign

Returns a new instance of Sign.



33
34
35
# File 'lib/sodium/sign.rb', line 33

def initialize(key)
  @key = self.class._secret_key(key)
end

Class Method Details

.keypairObject



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/sodium/sign.rb', line 6

def self.keypair
  public_key = Sodium::Buffer.empty self.implementation[:PUBLICKEYBYTES]
  secret_key = Sodium::Buffer.empty self.implementation[:SECRETKEYBYTES]

  self.implementation.nacl_keypair(
    public_key.to_ptr,
    secret_key.to_ptr
  ) or raise Sodium::CryptoError, 'failed to generate a keypair'

  return secret_key, public_key
end

.verify(key, message, signature) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/sodium/sign.rb', line 18

def self.verify(key, message, signature)
  key       = self._public_key(key)
  signature = self._signature(message, signature)
  message   = Sodium::Buffer.empty(signature.bytesize)
  mlen      = FFI::MemoryPointer.new(:ulong_long, 1, true)

  self.implementation.nacl_open(
    message   .to_ptr,
    mlen,
    signature .to_ptr,
    signature .bytesize,
    key       .to_ptr
  )
end

Instance Method Details

#sign(message) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/sodium/sign.rb', line 37

def sign(message)
  message   = self.class._message(message)
  signature = Sodium::Buffer.empty(message.bytesize + self.implementation[:BYTES])
  slen      = FFI::MemoryPointer.new(:ulong_long, 1, true)

  self.implementation.nacl(
    signature .to_ptr,
    slen,
    message   .to_ptr,
    message   .bytesize,
    @key      .to_ptr
  ) or raise Sodium::CryptoError, 'failed to generate signature'

  # signatures actually encode the message itself at the end, so we
  # slice off only the signature bytes
  signature.byteslice(
    0,
    slen.read_ulong_long - message.bytesize
  )
end