Working with openssl and files

Let me start out by saying all I do is in the name of science, I only
say this because what Im about to ask seems unreasonable. I’m trying
to:

1.) Take an existing ruby script
2.) Encrypt it
3.) Store the encrypted copy in another file
4.) Reopen that file
5.) Decrypt the contents
6.) eval the contents

I have some code so far, here is what it looks like:

require ‘openssl’

def encrypt(data, key, iv, cipher_type)
aes = OpenSSL::Cipher::Cipher.new(cipher_type)
aes.encrypt
aes.key = key
aes.iv = iv if iv != nil
aes.update(data) + aes.final
end

def decrypt(encrypted_data, key, iv, cipher_type)
aes = OpenSSL::Cipher::Cipher.new(cipher_type)
aes.decrypt
aes.key = key
aes.iv = iv if iv != nil
aes.update(encrypted_data) + aes.final
end

@key = “borgeddd”*4
@salt = nil
@algorithm = “AES-256-ECB”

file = File.new("./Ruby_Script.rb")

encrypted_file = File.open(“borged”, ‘w’)
encrypted_output = encrypt(file.read, @key, @salt, @algorithm)
encrypted_file.write(encrypted_output)

encrypted_file.close

file = File.open(“borged”)
decrypted_output = decrypt(file.read, @key, @salt, @algorithm) #works
if I just use the string encrypted_output
puts decrypted_output

eval decrypted_output

The code works if I just encrypt and decrypt strings, but when I write
to a file it appears its losing data. After encrypting the data and
looking at the length of the string its roughly about 1,000
characters, however, after I write to a file and close/reopen it the
new content is only about 300 characters long. That could be a bad
measurement, but it seems to me like Im losing something in the
translation. When I actually run this code as it is I get:

“C:/Workspace/Hob-nobbery/init.rb:16:in final': wrong final block length (OpenSSL::CipherError)" " from C:/Workspace/Hob-nobbery/init.rb:16:indecrypt’”

Any ideas?

On Wed, Aug 26, 2009 at 01:33:02AM +0900, Juston Davies wrote:

end
@salt = nil
@algorithm = “AES-256-ECB”

file = File.new("./Ruby_Script.rb")

encrypted_file = File.open(“borged”, ‘w’)

You probably need to open the file in binary write mode:

encrypted_file = File.open(“borged”, ‘wb’)

eval decrypted_output
“C:/Workspace/Hob-nobbery/init.rb:16:in final': wrong final block length (OpenSSL::CipherError)" " from C:/Workspace/Hob-nobbery/init.rb:16:indecrypt’”

Any ideas?

Try opening the file in binary write mode as I’ve written above. I
think that will work out the problems.

Well that did it. Wasn’t the write, but the read. Thanks a bunch!

On Aug 25, 11:16 am, Aaron P. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs