-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt.rb
67 lines (57 loc) · 1.79 KB
/
encrypt.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'openssl'
require 'base64'
require 'dotenv/load'
original_key = ENV['KEY']
desired_length = 32
file_path = './tester.jpg'
def duplicate_and_cut(original_key, desired_length)
duplicated_key = original_key.chars.cycle.take(desired_length).join
duplicated_key.slice(0, desired_length)
end
key = duplicate_and_cut(original_key, desired_length)
iv = OpenSSL::Cipher.new('AES-256-CBC').random_iv
def encrypt(plaintext, key, iv)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.encrypt
cipher.key = key
cipher.iv = iv
encrypted = cipher.update(plaintext) + cipher.final
encrypted.unpack1('H*')
encoded = Base64.strict_encode64(encrypted)
until encoded.end_with?('=') && !encoded.end_with?('==')
plaintext.prepend('\x00')
encrypted = cipher.update(plaintext) + cipher.final
encoded = Base64.strict_encode64(encrypted)
end
encoded
end
def inject_code(file_path, ciphertext)
if File.exist?(file_path)
puts "File '#{file_path}' found and being read."
else
puts "File '#{file_path}' not found."
return
end
magic_number = 'FFD8FF'
magic_number_bin = [magic_number].pack('H*')
File.open(file_path, 'r+b') do |file|
binary_data = file.read
index = binary_data.index(magic_number_bin)
if index.nil?
puts 'Magic number not found in the file.'
else
puts "Magic number found at index #{index} in the file."
file.seek(index + magic_number_bin.bytesize)
# test add @@ at the end of the ciphertext
file.write(ciphertext)
puts "Ciphertext: #{ciphertext}"
puts('Code injected successfully.')
end
end
end
print 'New message: '
plaintext = gets.chomp
plaintext = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + plaintext
ciphertext = encrypt(plaintext, key, iv)
# Encryption
inject_code(file_path, ciphertext)