Class: NETSNMP::Encryption::AES

Inherits:
Object
  • Object
show all
Defined in:
lib/netsnmp/encryption/aes.rb

Instance Method Summary collapse

Constructor Details

#initialize(priv_key, cipher:, local: 0) ⇒ AES

Returns a new instance of AES.



6
7
8
9
10
11
12
13
# File 'lib/netsnmp/encryption/aes.rb', line 6

def initialize(priv_key, cipher:, local: 0)
  @priv_key = priv_key
  @local = local
  # https://www.rfc-editor.org/rfc/rfc3826
  # https://snmp.com/snmpv3/snmpv3_aes256.shtml
  # Note: AES Blumental is not supported and not widely used
  @cipher = cipher
end

Instance Method Details

#decrypt(encrypted_data, salt:, engine_boots:, engine_time:) ⇒ Object

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/netsnmp/encryption/aes.rb', line 41

def decrypt(encrypted_data, salt:, engine_boots:, engine_time:)
  raise Error, "invalid priv salt received" unless !salt.empty? && (salt.length % 8).zero?

  cipher = case @cipher
           when :aes, :aes128 then OpenSSL::Cipher.new("aes-128-cfb")
           when :aes192 then OpenSSL::Cipher.new("aes-192-cfb")
           when :aes256 then OpenSSL::Cipher.new("aes-256-cfb")
           end
  cipher.padding = 0

  iv = generate_decryption_key(engine_boots, engine_time, salt)

  cipher.decrypt
  cipher.key = aes_key
  cipher.iv = case @cipher
              when :aes, :aes128 then iv[0..16]
              when :aes192 then iv[0..24]
              when :aes256 then iv[0..32]
              end
  decrypted_data = cipher.update(encrypted_data) + cipher.final

  hlen, bodylen = OpenSSL::ASN1.traverse(decrypted_data) { |_, _, x, y, *| break x, y }
  decrypted_data.byteslice(0, hlen + bodylen) || "".b
end

#encrypt(decrypted_data, engine_boots:, engine_time:) ⇒ Object



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
# File 'lib/netsnmp/encryption/aes.rb', line 15

def encrypt(decrypted_data, engine_boots:, engine_time:)
  cipher = case @cipher
           when :aes, :aes128 then OpenSSL::Cipher.new("aes-128-cfb")
           when :aes192 then OpenSSL::Cipher.new("aes-192-cfb")
           when :aes256 then OpenSSL::Cipher.new("aes-256-cfb")
           end

  iv, salt = generate_encryption_key(engine_boots, engine_time)

  cipher.encrypt
  cipher.iv = case @cipher
              when :aes, :aes128 then iv[0, 16]
              when :aes192 then iv[0, 24]
              when :aes256 then iv[0, 32]
              end
  cipher.key = aes_key

  if (diff = decrypted_data.length % 8) != 0
    decrypted_data << ("\x00" * (8 - diff))
  end

  encrypted_data = cipher.update(decrypted_data) + cipher.final

  [encrypted_data, salt]
end