Skip to content

Instantly share code, notes, and snippets.

@nuna
Created October 28, 2011 10:48
Show Gist options
  • Save nuna/1322057 to your computer and use it in GitHub Desktop.
Save nuna/1322057 to your computer and use it in GitHub Desktop.
base64 encode/decode
$ file test.png
test.png: PNG image data, 22 x 13, 16-bit grayscale, non-interlaced
$ md5sum test.png
c6db60c696981f908324d3365e0836c0 test.png
# base64 encoding with ruby 1.8.7
$ irb-ruby-1.8.7-p334
ruby-1.8.7-p334 :001 > RUBY_VERSION
=> "1.8.7"
ruby-1.8.7-p334 :002 > b64 = [File.read('test.png')].pack('m')
=> "iVBORw0KGgoAAAANSUhEUgAAABYAAAANEAAAAADYXh38AAAAAmJLR0T//xSr\nMc0AAAAJcEhZcwAAAEgAAABIAEbJaz4AAADMSURBVCjPY/hPAmD4/z88HL8S\nhDxQMQMDAfPg8gyRkQwM5ubvVOPjlZVlZHx8Hj4ECU+eLCsrKdnR8f8/RP73\nbyST4+J27PgHBJs2WVuDhDk4nj179crDA81kCIeHhwEKWFlBwvb2QUGrVn37\nhlUxF9fnzyDunz/PnoHo37937UpIsLDAovjv35CQwsJfv/7+bWiIjAQJa2h8\n+vTkCRcXRPHfv3DFhoYqKi9Nw8OlpGRkgoPfvAEJd3RISsrITJ0KYoPk4R4k\nKVIGg2IAI+rURZux+/IAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTEtMTAtMjhU\nMTk6Mjg6NTErMDk6MDBtp1cwAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDExLTEw\nLTI4VDE5OjI4OjUxKzA5OjAwHPrvjAAAAAp0RVh0bGFiZWwAdGVzdLvYsQ4A\nAAASdEVYdGxhYmVsOnBvaW50c2l6ZQAxMtFMvRcAAAAASUVORK5CYII=\n"
ruby-1.8.7-p334 :003 > File.open('test.txt', 'w+'){|f| f.write(b64)}
=> 606
$ irb-ruby-1.8.7-p334
ruby-1.8.7-p334 :001 > RUBY_VERSION
=> "1.8.7"
ruby-1.8.7-p334 :002 > require 'digest/md5'
=> true
ruby-1.8.7-p334 :003 > Digest::MD5.hexdigest(File.read('test.txt').unpack('m').first)
=> "c6db60c696981f908324d3365e0836c0"
ruby-1.8.7-p334 :004 > Digest::MD5.hexdigest(File.read('test.png'))
=> "c6db60c696981f908324d3365e0836c0"
$ irb-ruby-1.9.2-p290
ruby-1.9.2-p290 :001 > RUBY_VERSION
=> "1.9.2"
ruby-1.9.2-p290 :002 > require 'digest/md5'
=> true
ruby-1.9.2-p290 :003 > Digest::MD5.hexdigest(File.read('test.txt').unpack('m').first)
=> "c6db60c696981f908324d3365e0836c0"
ruby-1.9.2-p290 :004 > Digest::MD5.hexdigest(File.read('test.png'))
=> "c6db60c696981f908324d3365e0836c0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment