Skip to content

Instantly share code, notes, and snippets.

@OutlawAndy
Created November 16, 2023 22:43
Show Gist options
  • Save OutlawAndy/21cce0db6b94e574aabdfb6b66342b4e to your computer and use it in GitHub Desktop.
Save OutlawAndy/21cce0db6b94e574aabdfb6b66342b4e to your computer and use it in GitHub Desktop.
simple digital signature example in Ruby
require 'openssl'
class KeyGen
def initialize
@pkey = OpenSSL::PKey::RSA.new(2048)
@cipher = OpenSSL::Cipher.new('AES-256-CBC')
end
def public_key = @pkey.public_key
def secure_key(password) = @pkey.export(@cipher, password)
end
User = Struct.new(:name, :public_key, :secure_key) do
def generate_key_pair(password)
key_pair = KeyGen.new
self.public_key = key_pair.public_key
self.secure_key = key_pair.secure_key(password)
end
end
Signature = Struct.new(:user, :datetime, :reason, :data) do
def sign!(password)
decrypted_key = OpenSSL::PKey::RSA.new(user.secure_key, password)
@value = decrypted_key.sign(OpenSSL::Digest::SHA256.new, self.data)
end
def value
@value || raise('Signature not signed yet')
end
end
Document = Struct.new(:body, :signature, :public_key) do
def sign!(user, password:, reason: 'approval')
self.signature = Signature.new(user, Time.now, reason, body)
self.public_key = user.public_key
signature.sign!(password)
end
def valid_signature?
public_key.verify(OpenSSL::Digest::SHA256.new, signature.value, body)
end
end
@OutlawAndy
Copy link
Author

Example code used in my lightning talk, demonstrating OpenSSL for digital signatures in Ruby. Example usage in irb below.

irb -r ./esignature.rb

user = User.new('Andy')

user.generate_key_pair('P4SSW0RD1')
# => "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-256- ... \n-----END RSA PRIVATE KEY-----\n"

document = Document.new(<<~DOC)
  Duis proident qui nisi. Qui nisi proident occaecat aliqua aliquip id lorem.
  Proident occaecat aliqua aliquip id, lorem exercitation esse. Aliquip id
  lorem exercitati on esse. Lorem, exercitation esse sunt pariatur officia
  incididunt adipiscing. Sunt, pariatur officia incididunt. Incididunt
  adipiscing id proident amet. Id proident amet reprehenderit laborum anim.
  Amet reprehenderit laborum anim.

  Proident qui nisi proident occaecat aliqua aliquip. Nisi proident occaecat
  aliqua aliquip id lorem. Occaecat aliqua aliquip id, lorem. Id lorem exercitation
  esse sunt pariatur, officia. Esse sunt pariatur officia incididunt adipiscing, id.
DOC

document.sign!(user, password: 'P4SSW0RD1')
# => "\n\x0F\x0E\xD3}\x89\xCEuh\x7F?\x9C\x88\xF5\x84V\xB4\xE5fA\xB ...

document.valid_signature?
# => true

document.body << "**EDIT**"

document.valid_signature?
# => false

document.body = document.body.sub("**EDIT**", '')

document.valid_signature?
# => true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment