Created
November 16, 2023 22:43
-
-
Save OutlawAndy/21cce0db6b94e574aabdfb6b66342b4e to your computer and use it in GitHub Desktop.
simple digital signature example in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example code used in my lightning talk, demonstrating OpenSSL for digital signatures in Ruby. Example usage in
irbbelow.irb -r ./esignature.rb