Ruby On Rails: How to fix “ArgumentError: key must be 16 bytes” error

Why this error happen ?

The RAILS_MASTER_KEY needs to be EXACTLY 32 characters long, NO NEW LINE, NO ENDING SLASH.
Using “rails secret” generates a 128 character password, which exceeds the allowable length.

The details and reproduce steps are well commented on Github issue. https://github.com/rails/rails/issues/33528#issuecomment-412677795

This is a bug in Ruby On Rails version 5, it should have been fixed now (latest Rails version in the time of writing this post is version 6), but in case of you are working on projects which using Rails 5, you might face this problem just like me

Let’s fix it !

  1. Check the content length of your “master.key” file
wc -c config/master.key

# Ouput
32 config/master.key # This is OK !

# In case the length is not 32
33 config/master.key # oh ... This is not good !
  1. In case it’s 33 length, let’s find out the problem, get the content of the current “master.key” file
cat config/master.key

# Output
abcdef123456abcdef123456abcdef12

If we count the characters manually, they are 32 chars, WTF ?

Yea as I said, this could be NEW LINE chars in your “master.key” file …

Solution 1: Delete the “master.key” file, re-create new one with EXACTLY 32 chars

# Remove old key
rm config/master.key

# Re-create new one
echo "abcdef123456abcdef123456abcdef12" >> "config/master.key"

It’s should work as expected now !

EDITOR=vim rails credentials:edit

Solution 2: Set ENV variable “RAILS_MASTER_KEY” with your 32 chars content

export RAILS_MASTER_KEY=abcdef123456abcdef123456abcdef12

It’s should work as expected now !

EDITOR=vim rails credentials:edit

Anyway, I recommend you to fix your “master.key” file as Solution 1 above.

Conclusion

I hope this post help you solve your problem.

Happy coding !

Share this on: