Skip to content
Newer
Older
100644 33 lines (25 sloc) 1.32 KB
9066f69 @augustl Initial commit
authored Jun 29, 2012
1 # Use a secret to create a signature for any data.
2 #
3 # This method is commonly used for secure cookies. Rails does this, for
4 # example. The cookie data is public. A method like the one described here
5 # is used to create a signature based on a secret when the cookie is created.
6 # The actual cookie contains the cookie data itself, and the signature. When
7 # the framework receives a cookie, it creates a new signature for the cookie.
8 # If either the cookie data or the signature data changed, you know someone
9 # tampered with the cookie. The security lies in that only the ones that know
10 # the secret are able to create the correct signature.
11
12 require "openssl"
13
14 data = "This is some data"
15 secret = "cfa4f9980a2209f91145d912082dcbfd28484e4fe846df404ef417b57aae740b880820fe357b99e7"
16 signature = OpenSSL::HMAC.digest("sha1", secret, data)
17
18 payload = {:data => data, :signature => signature}
19
20 # Now send the payload to anyone.
21
22 # If the payload is not tampered with:
23 p payload[:signature] == OpenSSL::HMAC.digest("sha1", secret, payload[:data])
24 # => true
25
26 # If someone tampers with the signature or data, you'll know, because the
27 # signatures won't match
28
29 p payload[:signature] + "altered" == OpenSSL::HMAC.digest("sha1", secret, payload[:data])
30 # => false
31 p payload[:signature] == OpenSSL::HMAC.digest("sha1", secret, payload[:data] + "altered")
32 # => false
Something went wrong with that request. Please try again.