forked from Blade3xyz/blade3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.rb
More file actions
73 lines (52 loc) · 1.51 KB
/
crypto.rb
File metadata and controls
73 lines (52 loc) · 1.51 KB
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
68
69
70
71
72
73
# frozen_string_literal: true
require "openssl"
require "logger"
require "base64"
class Crypto
attr_accessor :key
attr_accessor :encrypted
attr_accessor :cipher
attr_accessor :key
def initialize(encrypted = true)
@encrypted = encrypted
@logger = Logger.new(STDOUT)
@mutex = Mutex.new
@logger.info "Initializing encryption using AES-256-CBC"
@cipher = OpenSSL::Cipher.new("aes-256-cbc")
if encrypted
@cipher.encrypt
else
@cipher.decrypt
end
if not File.exist?("blade3.key")
@key = @cipher.random_key
File.binwrite("blade3.key", @key)
@logger.debug "Wrote blade3 key to: ./blade3.key"
else
@key = File.binread("blade3.key")
@logger.debug "Imported key from ./blade3.key"
end
@cipher.key = @key
@cipher.iv = "0"*16
end
def encrypt(message)
unless @encrypted
raise "Encryption disabled for this Crypto instance!"
end
@mutex.synchronize {
final = Base64::encode64(@cipher.update(message) + @cipher.final)
@cipher.reset
final
}
end
def decrypt(message)
if @encrypted
raise "Encryption enabled for this Crypto instance!"
end
@mutex.synchronize {
final = @cipher.update(Base64::decode64(message)) + @cipher.final
@cipher.reset
final
}
end
end