Skip to content

Instantly share code, notes, and snippets.

@Aerotune
Last active December 31, 2015 08:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aerotune/7961606 to your computer and use it in GitHub Desktop.
Save Aerotune/7961606 to your computer and use it in GitHub Desktop.
Verify identity of sender of a message
require 'openssl'
key1 = OpenSSL::PKey::EC.new("secp112r1").generate_key
key2 = OpenSSL::PKey::EC.new("secp112r1").generate_key
shared_key1 = key1.dh_compute_key(key2.public_key)
shared_key2 = key2.dh_compute_key(key1.public_key)
## Shared secret key
#p shared_key1 == shared_key2
#p shared_key1
#p shared_key2
## HMAC
@digest = OpenSSL::Digest::SHA224.new
def verify key, message, signature
# used the method of comparison found in this article:
# https://blog.jcoglan.com/2012/06/09/why-you-should-never-use-hash-functions-for-message-authentication/
got = @digest.digest OpenSSL::HMAC.digest(@digest, key, message)
expected = @digest.digest signature
got == expected
end
message = "Hello!"
signature1 = OpenSSL::HMAC.digest @digest, shared_key1, message
signature2 = OpenSSL::HMAC.digest @digest, shared_key2, message
puts verify(shared_key1, message, signature2) ? "Verified" : "Not verified"
puts verify(shared_key2, message, signature1) ? "Verified" : "Not verified"
require 'openssl'
key = OpenSSL::PKey::EC.new("secp112r1").generate_key
#puts "Private Key:"
#p key.to_pem
## Recreate key from pem
#key = OpenSSL::PKey::EC.new(key.to_pem)
public_key = OpenSSL::PKey::EC.new("secp112r1")
public_key.public_key = key.public_key
#puts "Public Key:"
#p public_key.to_pem
## Recreate key from pem
#public_key = OpenSSL::PKey::EC.new(public_key.to_pem)
def verify key, message, signature
key.dsa_verify_asn1(message, signature)
end
message = 'Chunky Bacon'
signature = key.dsa_sign_asn1 message
## How to get the size of the signature
#signature_size = signature[1].ord + 2
#puts signature_size == signature.bytesize
## to make it fail
## try changing the signature
#signature[8] = 'a'
## or the message
#message['Chunky'] = 'Crunchy'
puts verify(public_key, message, signature) ? "Verified" : "Not verified!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment