Skip to content

Instantly share code, notes, and snippets.

@Tonkonozhenko
Created June 28, 2017 08:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tonkonozhenko/7d1ce5b9ab059e70826c64aa13b6ad25 to your computer and use it in GitHub Desktop.
Save Tonkonozhenko/7d1ce5b9ab059e70826c64aa13b6ad25 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'base64'
KEY_LENGTH = 2048
ENCRYPTION_KEY_LENGTH = 256
CIPHER_NAME = "aes-#{ENCRYPTION_KEY_LENGTH}-cfb"
class Hacker
class << self
attr_reader :public_key
def generate_keys!
@private_key = OpenSSL::PKey::RSA.new KEY_LENGTH
@public_key = @private_key.public_key
end
def pay_money(encrypted_key)
OpenSSL::PKey::RSA.new(@private_key).private_decrypt(encrypted_key)
end
end
end
class User
attr_reader :data, :encrypted_key
def initialize(data)
@data = data
end
def encrypt!(public_key)
# Encrypt data
cipher = OpenSSL::Cipher.new(CIPHER_NAME).tap(&:encrypt)
encryption_key = cipher.random_key + cipher.random_iv
@data = cipher.update(data) + cipher.final
# Encrypt key
@encrypted_key = OpenSSL::PKey::RSA.new(public_key).public_encrypt(encryption_key)
end
def decrypt!(encryption_key)
decipher = OpenSSL::Cipher.new(CIPHER_NAME).tap(&:decrypt)
decipher.key, decipher.iv = encryption_key[0...32], encryption_key[32...48]
@data = decipher.update(data) + decipher.final
end
end
Hacker.generate_keys!
2.times do |i|
data = "Data ##{i}!"
user = User.new(data)
user.encrypt!(Hacker.public_key)
puts "Data encrypted? #{data != user.data}"
decrypted_key = Hacker.pay_money(user.encrypted_key)
user.decrypt!(decrypted_key)
puts "Encryption key:\n#{Base64.encode64(decrypted_key)}"
puts "Encrypted key:\n#{Base64.encode64(user.encrypted_key)}"
puts "Data decrypted? #{data == user.data}"
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment