i'm trying to do a sample app, for testing purposes vs other people development, and would like to print to the screen the encrypted string, and put it back to a decrypt mechanism....I just don't seem to be finding the way to do this...I've tried base64 and unpack, and feel this is the way, but am not getting there.
require 'openssl'
require 'base64'
def ask(prompt)
loop do
print prompt, ' '
$stdout.flush
s = gets
return s.chomp
end
end
def aes(m,k,t)
(aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(m)).key = Digest::SHA256.digest(k)
aes.update(t) << aes.final
end
def encrypt(key, text)
aes(:encrypt, key, text)
end
def decrypt(key, text)
aes(:decrypt, key, text)
end
def my_decrypt
@crypted = ask("Crypted data: ")
decrypted = decrypt("12345678911131511192123252729412",@crypted)
print decrypted
end
def my_encrypt
@decrypted = ask("Data to encrypt: ")
crypted = encrypt("12345678911131511192123252729412",@decrypted)
print crypted
end
option=ask("Option 1 - Encrypt, 2 decrypt")
case option
when "1" then my_encrypt
when "2" then my_decrypt
else print "Option not valid"
end
Anyone to the rescue?
Thank you
After some fight, i finally got it...I just need to convert the binary to Hex, and then back to binary...
Two notes : to convert a binary to hex, you can use String.unpack, which will return an array. To convert an hex to binary, you first need to build it as an array ["anystringhere"] , and then pack it back to binary using Array.pack
Here is the resulting code
require 'openssl'
require 'base64'
def ask(prompt)
loop do
print prompt, ' '
$stdout.flush
s = gets
return s.chomp
end
end
def aes(m,k,t)
(aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(m)).key = Digest::SHA256.digest(k)
aes.update(t) << aes.final
end
def encrypt(key, text)
aes(:encrypt, key, text)
end
def decrypt(key, text)
aes(:decrypt, key, text)
end
def my_decrypt
@crypted = ask("Crypted data: ")
decrypted = decrypt("12345678911131517192123252729313",[@crypted].pack('H*'))
print decrypted
end
def my_encrypt
@decrypted = ask("Data to encrypt: ")
crypted = encrypt("12345678911131517192123252729313",@decrypted)
print u=crypted.unpack('H*')
end
option=ask("Option 1 - Encrypt, 2 decrypt")
case option
when "1" then my_encrypt
when "2" then my_decrypt
else print "Option not valid"
end