From: "Martin Boßlet" Date: 2012-05-17T10:18:56+09:00 Subject: Re: ruby openssl bug, reset cipher fails 2012/5/17 roob noob : > This is mentioned in this thread > http://www.ruby-forum.com/topic/4293246#1061067  but I thought it was a > different problem then so the thread isn't named correctly. Hopefully > this will get the attention of people interested more in OpenSSL than in > helping noobs understand initialize. > > > ruby 1.9.3p125 [x86_64-linux] > > > irb(main):001:0> require 'openssl' > => true > irb(main):002:0> message = "whatever" > => "whatever" > irb(main):003:0> @sha256 = OpenSSL::Digest::SHA256.new > => # e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855> > irb(main):004:0> @cipher = OpenSSL::Cipher::Cipher.new("AES-256-CTR") > => # > irb(main):005:0> 2.times do > irb(main):006:1* key = @sha256.digest("whatever") > irb(main):007:1> @sha256.reset > irb(main):008:1> @cipher.encrypt > irb(main):009:1> @cipher.key = key > irb(main):010:1> ciphertext = @cipher.update(message) > irb(main):011:1> ciphertext << @cipher.final > irb(main):012:1> @cipher.reset > irb(main):013:1> puts ciphertext > irb(main):014:1> end > �a�xtT�� > 9]K���/ > => 2 > > -- > Posted via http://www.ruby-forum.com/. Hi, this is not a bug and Cipher#reset is working fine. What's "going wrong" here is that you also have to take the IV into account when trying to reproduce a certain ciphertext. In fact, you don't even need to call #reset explicitly, #encrypt implies the same functionality already. Let me explain: require 'openssl' message = "whatever" sha256 = OpenSSL::Digest::SHA256.new cipher = OpenSSL::Cipher::Cipher.new("AES-256-CTR") iv = "0" * 32 # you shouldn't do this of course, see my remarks below 2.times do key = sha256.digest("whatever") sha256.reset cipher.encrypt cipher.key = key cipher.iv = iv ciphertext = cipher.update(message) ciphertext << cipher.final #cipher.reset puts ciphertext #will reproduce the same ciphertext twice end Of course, it's bad practice to choose a deterministic IV like that, it was just for demonstration. Generally, you should prefer to use #random_iv and #random_key in production code as outlined in http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/Cipher.html. Hope that clarifies the issue? -Martin