Skip to content

Instantly share code, notes, and snippets.

@Jwata
Last active November 23, 2019 10:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jwata/4e5122fa43d719400914716955872cc2 to your computer and use it in GitHub Desktop.
Save Jwata/4e5122fa43d719400914716955872cc2 to your computer and use it in GitHub Desktop.
Calculate Rails CSRF token stored in session from authenticity token

On your rails project root

git clone https://gist.github.com/Jwata/4e5122fa43d719400914716955872cc2 authenticity_token_to_csrf_token

rails runner ./authenticity_token_to_csrf_token/calculate.rb 'some_authenticity_token'
=> 2PqIaqHja/+PllheC7mStH2X+y/E69LlyS5AIfd9MVs= # this is the csrf token stored in your session
#!/usr/bin/env ruby
authenticity_token = ARGV[0]
# decode
masked_token = Base64.strict_decode64(authenticity_token)
# unmask
one_time_pad = masked_token[0...31]
encrypted_csrf_token = masked_token[32..-1]
encrypted_csrf_token_bytes = encrypted_csrf_token.bytes
one_time_pad.each_byte.with_index { |c, i| encrypted_csrf_token_bytes[i] ^= c }
csrf_token = encrypted_csrf_token_bytes.pack("C*")
puts Base64.encode64(csrf_token)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment