-
Notifications
You must be signed in to change notification settings - Fork 0
/
fipscryptor.rb
83 lines (70 loc) · 2.41 KB
/
fipscryptor.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# fipscryptor.rb - simple Ruby encryptor which will work when using OpenSSL FIPS mode
# Author: Sandy Cash <[email protected]>
#
# Note: enabling OpenSSL FIPS mode is up to the user. FIPS mode is not required
# for this encryptor to work.
require 'openssl'
require 'base64'
class Fipscryptor
class << self
ALGORITHM = 'AES-256-CFB'.freeze
# Generate a PKCS5 encryption key with some reasonable defaults
def generate_key(passphrase, salt)
iter = 200000
key_len = 32
OpenSSL::PKCS5.pbkdf2_hmac_sha1(passphrase, salt, iter, key_len)
end
# def generate_key(passphrase, salt)
# return nil unless ( passphrase && salt )
# passphrase
# end
# Return a random sequence of eight bytes
def generate_salt
OpenSSL::Random.random_bytes(8).to_s
end
# Return a random sequence of at least 16 bytes and at most 186 bytes
# The maximum is to ensure that the base64-encoded length is <= 256
def generate_iv(len)
if (len < 16)
len = 16
elsif (len > 186)
len = 186
end
OpenSSL::Random.random_bytes(len).to_s
end
def generate_cipher(algo)
unless algo
algo = ALGORITHM
end
OpenSSL::Cipher.new(algo)
end
def encrypt(cipher, plaintext, key, iv)
cipher.reset
cipher.encrypt
cipher.key=(key)
cipher.iv=(iv)
cipher.update(plaintext).tap { |output| output << cipher.final }
end
# Return the base64-encoded join of iv.length+iv+encrypted
# Only works if all IVs have a length <= 186. This means that the length
# of the base-64 encoded IV will be <= 256, which is a single-byte value.
# (single byte => 4 chars when encoded)
def encrypt_and_package(cipher, plaintext, key, iv)
iv_enc = Base64.strict_encode64(iv)
Base64.strict_encode64(iv_enc.length.to_s).tap { |output| output << iv_enc << Base64.strict_encode64(encrypt(cipher, plaintext, key, iv)) }
end
def decrypt(cipher, encrypted, key, iv)
cipher.reset
cipher.decrypt
cipher.key=(key)
cipher.iv=(iv)
cipher.update(encrypted).tap { |output| output << cipher.final }
end
# First decode the base64-encoded string, trim the iv from the front, then decrypt
def decode_and_decrypt(cipher, encoded, key)
iv_enc_len = Base64.decode64(encoded[0,4]).to_i
iv = Base64.decode64(encoded[4, iv_enc_len])
decrypt(cipher, Base64.decode64(encoded[4 + iv_enc_len, encoded.length - (4 + iv_enc_len)]), key, iv)
end
end
end