¿Cómo puedo convertir una cadena binaria codificada de Blowfish a ASCII en Ruby?
-
03-07-2019 - |
Pregunta
Me gustaría codificar un texto simple usando Ruby y la biblioteca de criptas . Me gustaría entonces transmitir este texto cifrado (junto con algunos otros datos) como una cadena hexadecimal ASCII dentro de un archivo XML.
Tengo el siguiente fragmento de código:
require 'rubygems'
require 'crypt/blowfish'
plain = "This is the plain text"
puts plain
blowfish = Crypt::Blowfish.new("A key up to 56 bytes long")
enc = blowfish.encrypt_block(plain)
puts enc
Qué resultados:
This is the plain text ????;
Creo que necesito llamar a enc.unpack ()
pero no estoy seguro de qué parámetros son necesarios para la llamada al método de desempaquetar.
Solución
Cuando dices " ASCII hexadecimal " ¿Quiere decir que simplemente debe ser ASCII legible o tiene que ser estrictamente hexadecimal?
Aquí hay dos enfoques para codificar datos binarios:
require 'rubygems'
require 'crypt/blowfish'
plain = "This is the plain text"
puts plain
blowfish = Crypt::Blowfish.new("A key up to 56 bytes long")
enc = blowfish.encrypt_string(plain)
hexed = ''
enc.each_byte { |c| hexed << '%02x' % c }
puts hexed
# => 9162f6c33729edd44f5d034fb933ec38e774460ccbcf4d451abf4a8ead32b32a
require 'base64'
mimed = Base64.encode64(enc)
puts mimed
# => kWL2wzcp7dRPXQNPuTPsOOd0RgzLz01FGr9Kjq0ysyo=
Otros consejos
Si usas decrypt_string
y su contraparte encrypt_string
lo genera con bastante facilidad. :)
require 'rubygems'
require 'crypt/blowfish'
plain = "This is the plain text"
puts plain
blowfish = Crypt::Blowfish.new("A key up to 56 bytes long")
enc = blowfish.encrypt_string(plain)
p blowfish.decrypt_string(enc)
También encontré esta publicación de blog que habla sobre problemas de velocidad usando la biblioteca Crypt, agregada solo como referencia. :)
http://basic70tech.wordpress.com/2007/03/09/blowfish-decryption-in- ruby /