Add SignatureService
This commit is contained in:
parent
d1b5bc6835
commit
714ebda2fe
5 changed files with 63 additions and 0 deletions
2
Gemfile
2
Gemfile
|
@ -58,6 +58,8 @@ gem 'fog-openstack'
|
|||
|
||||
gem 'pg'
|
||||
|
||||
gem 'rbnacl-libsodium'
|
||||
|
||||
gem 'rgeo-geojson'
|
||||
gem 'leaflet-rails'
|
||||
gem 'leaflet-markercluster-rails', '~> 0.7.0'
|
||||
|
|
|
@ -591,6 +591,10 @@ GEM
|
|||
rb-fsevent (0.10.2)
|
||||
rb-inotify (0.9.10)
|
||||
ffi (>= 0.5.0, < 2)
|
||||
rbnacl (5.0.0)
|
||||
ffi
|
||||
rbnacl-libsodium (1.0.16)
|
||||
rbnacl (>= 3.0.1)
|
||||
rbovirt (0.1.5)
|
||||
nokogiri
|
||||
rest-client (> 1.7.0)
|
||||
|
@ -836,6 +840,7 @@ DEPENDENCIES
|
|||
rack-mini-profiler
|
||||
rails (~> 5.2.0.rc1)
|
||||
rails-controller-testing
|
||||
rbnacl-libsodium
|
||||
rest-client
|
||||
rgeo-geojson
|
||||
rspec-rails
|
||||
|
|
38
app/services/signature_service.rb
Normal file
38
app/services/signature_service.rb
Normal file
|
@ -0,0 +1,38 @@
|
|||
class SignatureService
|
||||
CONFIG_PATH = Rails.root.join("config", "signing_key.yml")
|
||||
|
||||
class << self
|
||||
def generate
|
||||
RbNaCl::Util.bin2hex(RbNaCl::SigningKey.generate)
|
||||
end
|
||||
|
||||
def verify(signature, message)
|
||||
message = Base64.urlsafe_encode64(message)
|
||||
begin
|
||||
signing_key.verify_key
|
||||
.verify(RbNaCl::Util.hex2bin(signature), message)
|
||||
rescue RbNaCl::BadSignatureError, RbNaCl::LengthError
|
||||
return false
|
||||
end
|
||||
end
|
||||
|
||||
def sign(message)
|
||||
message = Base64.urlsafe_encode64(message)
|
||||
RbNaCl::Util.bin2hex(signing_key.sign(message))
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def signing_key
|
||||
@@signing_key ||= RbNaCl::SigningKey.new(RbNaCl::Util.hex2bin(config[:key]))
|
||||
end
|
||||
|
||||
def config
|
||||
if File.exist?(CONFIG_PATH)
|
||||
YAML.safe_load(File.read(CONFIG_PATH)).symbolize_keys
|
||||
else
|
||||
{}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
2
config/signing_key.yml
Normal file
2
config/signing_key.yml
Normal file
|
@ -0,0 +1,2 @@
|
|||
# This is a signing key used in dev and test environments
|
||||
key: 'aef3153a9829fa4ba10acb02927ac855df6b92795b1ad265d654443c4b14a017'
|
16
spec/services/signature_service_spec.rb
Normal file
16
spec/services/signature_service_spec.rb
Normal file
|
@ -0,0 +1,16 @@
|
|||
require 'spec_helper'
|
||||
|
||||
describe SignatureService do
|
||||
let(:service) { SignatureService }
|
||||
let(:message) { { hello: 'World!' }.to_json }
|
||||
let(:message2) { { hello: 'World' }.to_json }
|
||||
|
||||
it "sign and verify" do
|
||||
signature = service.sign(message)
|
||||
signature2 = service.sign(message2)
|
||||
|
||||
expect(service.verify(signature, message)).to eq(true)
|
||||
expect(service.verify(signature2, message)).to eq(false)
|
||||
expect(service.verify(signature, message2)).to eq(false)
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue