Module: EasyAI::Base::FileCrypto

Defined in:
lib/easyai/base/file_crypto.rb

Class Method Summary collapse

Class Method Details

.aes_128_ecb_decrypt(key, encrypted_data) ⇒ Object

AES-128-ECB 解密字符串



27
28
29
30
31
32
33
# File 'lib/easyai/base/file_crypto.rb', line 27

def self.aes_128_ecb_decrypt(key, encrypted_data)
  cipher = OpenSSL::Cipher.new('AES-128-ECB')
  cipher.decrypt
  cipher.key = key
  decrypted_data = Base64.strict_decode64(encrypted_data)
  cipher.update(decrypted_data) + cipher.final
end

.aes_128_ecb_encrypt(key, data) ⇒ Object

AES-128-ECB 加密字符串



18
19
20
21
22
23
24
# File 'lib/easyai/base/file_crypto.rb', line 18

def self.aes_128_ecb_encrypt(key, data)
  cipher = OpenSSL::Cipher.new('AES-128-ECB')
  cipher.encrypt
  cipher.key = key
  encrypted = cipher.update(data) + cipher.final
  Base64.strict_encode64(encrypted)
end

.decrypt_directory(dir_path, password, output_dir = nil) ⇒ Object

解密目录中的所有加密文件



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/easyai/base/file_crypto.rb', line 139

def self.decrypt_directory(dir_path, password, output_dir = nil)
  raise "目录不存在: #{dir_path}" unless File.exist?(dir_path)
  raise "指定路径不是目录: #{dir_path}" unless File.directory?(dir_path)
  
  # 如果没有指定输出目录,智能判断输出路径
  if output_dir.nil?
    if dir_path.end_with?('_encrypted')
      output_dir = dir_path.gsub(/_encrypted$/, '')
    else
      output_dir = "#{dir_path}_decrypted"
    end
  end
  
  # 创建输出目录
  Dir.mkdir(output_dir) unless File.exist?(output_dir)
  
  decrypted_files = []
  
  # 遍历目录中的所有文件(递归)
  Dir.glob(File.join(dir_path, "**", "*")).each do |file_path|
    next unless File.file?(file_path)
    
    # 计算相对路径
    relative_path = file_path.gsub(/^#{Regexp.escape(dir_path)}\//, '')
    
    # 智能处理输出文件路径
    if relative_path.end_with?('.encrypted')
      # 移除 .encrypted 后缀
      output_relative_path = relative_path.gsub(/\.encrypted$/, '')
    else
      # 如果不是 .encrypted 文件,跳过或添加 .decrypted 后缀
      puts "⚠️  跳过非加密文件: #{relative_path}"
      next
    end
    
    output_file_path = File.join(output_dir, output_relative_path)
    
    # 确保输出文件的目录存在
    output_file_dir = File.dirname(output_file_path)
    FileUtils.mkdir_p(output_file_dir) unless File.exist?(output_file_dir)
    
    begin
      decrypt_file(file_path, password, output_file_path)
      decrypted_files << output_file_path
    rescue => e
      puts "⚠️  跳过文件 #{relative_path}: #{e.message}"
    end
  end
  
  { output_dir: output_dir, decrypted_files: decrypted_files }
rescue => e
  raise "解密目录失败: #{e.message}"
end

.decrypt_file(file_path, password, output_path = nil) ⇒ Object

解密文件



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/easyai/base/file_crypto.rb', line 108

def self.decrypt_file(file_path, password, output_path = nil)
  raise "文件不存在: #{file_path}" unless File.exist?(file_path)
  raise "指定路径不是文件: #{file_path}" unless File.file?(file_path)
  
  # 如果没有指定输出路径,移除 .encrypted 后缀或加 .decrypted 后缀
  if output_path.nil?
    if file_path.end_with?('.encrypted')
      output_path = file_path.gsub(/\.encrypted$/, '')
    else
      output_path = "#{file_path}.decrypted"
    end
  end
  
  # 生成密钥
  key = generate_key(password)
  
  # 读取加密文件内容
  encrypted_content = File.read(file_path)
  
  # 解密内容
  decrypted_content = aes_128_ecb_decrypt(key, encrypted_content)
  
  # 写入解密文件
  File.write(output_path, decrypted_content)
  
  output_path
rescue => e
  raise "解密文件失败: #{e.message}"
end

.encrypt_directory(dir_path, password, output_dir = nil) ⇒ Object

加密目录中的所有文件



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/easyai/base/file_crypto.rb', line 66

def self.encrypt_directory(dir_path, password, output_dir = nil)
  raise "目录不存在: #{dir_path}" unless File.exist?(dir_path)
  raise "指定路径不是目录: #{dir_path}" unless File.directory?(dir_path)
  
  # 如果没有指定输出目录,使用原目录路径加 _encrypted 后缀
  output_dir ||= "#{dir_path}_encrypted"
  
  # 创建输出目录
  Dir.mkdir(output_dir) unless File.exist?(output_dir)
  
  encrypted_files = []
  
  # 遍历目录中的所有文件(递归)
  Dir.glob(File.join(dir_path, "**", "*")).each do |file_path|
    next unless File.file?(file_path)
    
    # 计算相对路径
    relative_path = file_path.gsub(/^#{Regexp.escape(dir_path)}\//, '')
    output_file_path = File.join(output_dir, "#{relative_path}.encrypted")
    
    # 确保输出文件的目录存在
    output_file_dir = File.dirname(output_file_path)
    FileUtils.mkdir_p(output_file_dir) unless File.exist?(output_file_dir)
    
    begin
      # 如果是 JSON 文件,先验证
      if file_path.downcase.end_with?('.json')
        validate_json_file(file_path)
      end
      encrypt_file(file_path, password, output_file_path)
      encrypted_files << output_file_path
    rescue => e
      puts "⚠️  跳过文件 #{relative_path}: #{e.message}"
    end
  end
  
  { output_dir: output_dir, encrypted_files: encrypted_files }
rescue => e
  raise "加密目录失败: #{e.message}"
end

.encrypt_file(file_path, password, output_path = nil) ⇒ Object

加密文件



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
# File 'lib/easyai/base/file_crypto.rb', line 36

def self.encrypt_file(file_path, password, output_path = nil)
  raise "文件不存在: #{file_path}" unless File.exist?(file_path)
  raise "指定路径不是文件: #{file_path}" unless File.file?(file_path)

  # 如果是 JSON 文件,验证其有效性
  if file_path.downcase.end_with?('.json')
    validate_json_file(file_path)
  end

  # 如果没有指定输出路径,使用原文件路径加 .encrypted 后缀
  output_path ||= "#{file_path}.encrypted"

  # 生成密钥
  key = generate_key(password)

  # 读取文件内容
  file_content = File.read(file_path)

  # 加密内容
  encrypted_content = aes_128_ecb_encrypt(key, file_content)

  # 写入加密文件
  File.write(output_path, encrypted_content)

  output_path
rescue => e
  raise "加密文件失败: #{e.message}"
end

.generate_key(password) ⇒ Object

生成 AES-128 密钥



13
14
15
# File 'lib/easyai/base/file_crypto.rb', line 13

def self.generate_key(password)
  Digest::MD5.hexdigest(password)[0, 16]
end

.get_password(prompt = "请输入密码: ") ⇒ Object

获取用户密码输入



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/easyai/base/file_crypto.rb', line 225

def self.get_password(prompt = "请输入密码: ")
  # 如果设置了环境变量,直接使用(主要用于测试和脚本自动化)
  if ENV['EASYAI_TEST_PASSWORD']
    password = ENV['EASYAI_TEST_PASSWORD']
    puts "使用环境变量密码"
    return password
  end

  begin
    print prompt
    password = STDIN.noecho(&:gets)&.chomp
    puts # 换行

    if password.nil? || password.empty?
      puts "❌ 密码不能为空"
      return nil
    end

    password
  rescue Interrupt
    puts "\n\n用户取消输入"
    return nil
  rescue => e
    puts "\n❌ 密码输入出错: #{e.message}"
    return nil
  end
end

.validate_json_file(file_path) ⇒ Object

验证 JSON 文件的有效性



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/easyai/base/file_crypto.rb', line 194

def self.validate_json_file(file_path)
  begin
    content = File.read(file_path)
    # 尝试解析 JSON
    JSON.parse(content)
  rescue JSON::ParserError => e
    # 提取错误位置信息
    error_msg = e.message
    puts "\n⚠️  警告: JSON 文件格式无效"
    puts "    文件: #{File.basename(file_path)}"
    puts "    路径: #{file_path}"
    puts "    错误: #{error_msg}"
    puts "\n是否继续加密这个无效的 JSON 文件?(y/n)"
    print "> "

    begin
      response = STDIN.gets&.chomp&.downcase
      unless response == 'y' || response == 'yes'
        raise "用户取消了对无效 JSON 文件的加密"
      end
      puts "继续加密文件..."
    rescue Interrupt
      raise "用户中断操作"
    end
  rescue => e
    # 文件读取错误等其他问题
    raise "验证 JSON 文件失败: #{e.message}"
  end
end