简体   繁体   中英

Gracefully re-encrypting tokens in Rails app

I inherited a Rails app that integrates with Facebook and encrypts a token sent from Facebook, which it saves as a user's identifying auth token.

For a variety of reasons, I ended up updating my Ruby, and some Gemfile changes have occurred which are causing issues with the app. The most significant one is a change to attr_encrypted , which, through the encrypted gem, handles the encryption of that Facebook token as it's saved to the database.

The trouble is, the app, which is live and already has many users, has an base secret encryption key that is too short for the newly updated attr_encrypted 's security standards. Specifically, when I try to encrypt a token now (in tests for now; I haven't pushed these changes live), an error is thrown saying that the key needs to be 32 bytes.

The question:

Does anyone have a suggestion for updating to a more secure token? If I change the token, I assume that will break decryption of the token, so that I, potentially permanently, lose the ability to read/use all the user identity tokens in the database. That's obviously pretty problematic, so I wanted to double check my thinking here.

My current thought is a migration: Run a migration that loops through each identity, decrypts the stored token using my old key, and then saves a newly-encrypted token with a new, longer key.

Then I can get rid of the old key without any issues. Right? Any issues anyone can think of regarding the peculiarities of the attr_encrypted gem or issues with encryption generally that I might not be thinking about?

I see no problem with the migration as you have proposed it.

It seems the documentation has a helpful suggestion:

If your key is insufficient length relative to the algorithm that you use, you should also pass in insecure_mode: true; this will prevent Encryptor from raising an exception regarding insufficient key length. Please see the Deprecations sections for more details including an example of how to specify your model with default options from attr_encrypted v1.x.

This means that you can use the new version of attr-encrypted to run the migration as you proposed.

You should first do a dry run in order to see if all your keys and tokens were created equally and are able to be migrated in the same way. If they are, then you can run the re-encryption.

The full story looks like it's covered in that gem's issue#109 :

1. Load all instances of Foo
2. Change key by redefining self.encryption_key
3. Save all instances of Foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM