@@ -165,12 +165,52 @@ def initialize(secret, sign_secret = nil, cipher: nil, digest: nil, serializer:
165
165
166
166
# Encrypt and sign a message. We need to sign the message in order to avoid
167
167
# padding attacks. Reference: https://www.limited-entropy.com/padding-oracle-attacks/.
168
+ #
169
+ # ==== Options
170
+ #
171
+ # [+:expires_at+]
172
+ # The datetime at which the message expires. After this datetime,
173
+ # verification of the message will fail.
174
+ #
175
+ # message = encryptor.encrypt_and_sign("hello", expires_at: Time.now.tomorrow)
176
+ # encryptor.decrypt_and_verify(message) # => "hello"
177
+ # # 24 hours later...
178
+ # encryptor.decrypt_and_verify(message) # => nil
179
+ #
180
+ # [+:expires_in+]
181
+ # The duration for which the message is valid. After this duration has
182
+ # elapsed, verification of the message will fail.
183
+ #
184
+ # message = encryptor.encrypt_and_sign("hello", expires_in: 24.hours)
185
+ # encryptor.decrypt_and_verify(message) # => "hello"
186
+ # # 24 hours later...
187
+ # encryptor.decrypt_and_verify(message) # => nil
188
+ #
189
+ # [+:purpose+]
190
+ # The purpose of the message. If specified, the same purpose must be
191
+ # specified when verifying the message; otherwise, verification will fail.
192
+ # (See #decrypt_and_verify.)
168
193
def encrypt_and_sign ( value , expires_at : nil , expires_in : nil , purpose : nil )
169
194
verifier . generate ( _encrypt ( value , expires_at : expires_at , expires_in : expires_in , purpose : purpose ) )
170
195
end
171
196
172
197
# Decrypt and verify a message. We need to verify the message in order to
173
198
# avoid padding attacks. Reference: https://www.limited-entropy.com/padding-oracle-attacks/.
199
+ #
200
+ # ==== Options
201
+ #
202
+ # [+:purpose+]
203
+ # The purpose that the message was generated with. If the purpose does not
204
+ # match, +decrypt_and_verify+ will return +nil+.
205
+ #
206
+ # message = encryptor.encrypt_and_sign("hello", purpose: "greeting")
207
+ # encryptor.decrypt_and_verify(message, purpose: "greeting") # => "hello"
208
+ # encryptor.decrypt_and_verify(message) # => nil
209
+ #
210
+ # message = encryptor.encrypt_and_sign("bye")
211
+ # encryptor.decrypt_and_verify(message) # => "bye"
212
+ # encryptor.decrypt_and_verify(message, purpose: "greeting") # => nil
213
+ #
174
214
def decrypt_and_verify ( data , purpose : nil , **)
175
215
_decrypt ( verifier . verify ( data ) , purpose )
176
216
end
0 commit comments