Class: NETSNMP::Encryption::DES

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

Instance Method Summary collapse

Constructor Details

#initialize(priv_key, local: 0) ⇒ DES

Returns a new instance of DES.



7
8
9
10
# File 'lib/netsnmp/encryption/des.rb', line 7

def initialize(priv_key, local: 0)
  @priv_key = priv_key
  @local = local
end

Instance Method Details

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

Raises:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/netsnmp/encryption/des.rb', line 32

def decrypt(encrypted_data, salt: , engine_boots: nil, engine_time: nil)
  raise Error, "invalid priv salt received" unless salt.length % 8 == 0
  raise Error, "invalid encrypted PDU received" unless encrypted_data.length % 8 == 0

  cipher = OpenSSL::Cipher::DES.new(:CBC)
  cipher.padding = 0

  iv = generate_decryption_key(salt)

  cipher.decrypt
  cipher.key = des_key
  cipher.iv = iv
  decrypted_data = cipher.update(encrypted_data) + cipher.final
  NETSNMP.debug {"decrypted:\n#{Hexdump.dump(decrypted_data)}" }

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

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



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/netsnmp/encryption/des.rb', line 13

def encrypt(decrypted_data, engine_boots: , engine_time: nil)
  cipher = OpenSSL::Cipher::DES.new(:CBC)

  iv, salt = generate_encryption_key(engine_boots)

  cipher.encrypt
  cipher.iv = iv
  cipher.key = des_key

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


  encrypted_data = cipher.update(decrypted_data) + cipher.final
  NETSNMP.debug {"encrypted:\n#{Hexdump.dump(encrypted_data)}" }
  [encrypted_data, salt]
end