Skip to content

Instantly share code, notes, and snippets.

@cesare
Created August 2, 2011 01:14
Show Gist options
  • Save cesare/1119390 to your computer and use it in GitHub Desktop.
Save cesare/1119390 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'base64'
require 'digest'
require 'openssl'
def encode(cryptkey, iv, cleardata)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.encrypt
cipher.key = cryptkey
cipher.iv = iv
encrypted = ''
encrypted << cipher.update(cleardata)
encrypted << cipher.final
encrypted
end
def decode(cryptkey, iv, secretdata)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.decrypt
cipher.key = cryptkey
cipher.iv = iv
decrypted = ''
decrypted << cipher.update(secretdata)
decrypted << cipher.final
decrypted
end
def flipByte(original, index)
bytes = original.unpack("C*")
bytes[index] ^= 0xff
bytes.pack("C*")
end
cryptkey = Digest::SHA256.digest('Nixnogen')
iv = 'a2xhcgAAAAAAAAAA'
buf = "Here is some data for the coding" # 32 chars
enc = encode(cryptkey, iv, buf)
puts "Encoded length: #{enc.length}"
puts "Encoded in hex: " + enc.unpack("H*").first
puts "Decode original " + decode(cryptkey, iv, enc)
enc = flipByte(enc, 31)
puts "Encoded in hex: " + enc.unpack("H*").first
puts "Decode original " + decode(cryptkey, iv, enc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment