Friday, 26 July 2019

How to require PHP.serialize to be able to verify a webhook? (Ruby on Rails 5)

I'm using Ruby on Rails 5, and ruby -v 2.5.3. I'm trying to verify a webhook, and the example says:

require 'base64'
require 'php_serialize'
require 'openssl'


public_key = '-----BEGIN PUBLIC KEY-----
MIICIjANBgkqh...'

# 'data' represents all of the POST fields sent with the request.
# Get the p_signature parameter & base64 decode it.
signature = Base64.decode64(data['p_signature'])

# Remove the p_signature parameter
data.delete('p_signature')

# Ensure all the data fields are strings
data.each {|key, value|data[key] = String(value)}

# Sort the data
data_sorted = data.sort_by{|key, value| key}

# and serialize the fields
# serialization library is available here: https://github.com/jqr/php-serialize
data_serialized = PHP.serialize(data_sorted, true)

# verify the data
digest    = OpenSSL::Digest::SHA1.new
pub_key   = OpenSSL::PKey::RSA.new(public_key).public_key
verified  = pub_key.verify(digest, signature, data_serialized)

if verified
    puts "Yay! Signature is valid!"
else
    puts "The signature is invalid!"
end

My problem is the php.serialize, I tried to use the gem: https://github.com/jqr/php-serialize, but that doesn't support ruby -v 2.5.3. (For example due to: https://github.com/jqr/php-serialize/issues/16)

How can I require 'php_serialize' in my Rails app?



from How to require PHP.serialize to be able to verify a webhook? (Ruby on Rails 5)

No comments:

Post a Comment