Module: MqttRails::SSLHelper

Extended by:
SSLHelper
Included in:
SSLHelper
Defined in:
lib/mqtt_rails/ssl_helper.rb

Instance Method Summary collapse

Instance Method Details

#config_ssl_context(cert_path = nil, key_path = nil, ca_path = nil) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/mqtt_rails/ssl_helper.rb', line 21

def config_ssl_context(cert_path=nil, key_path=nil, ca_path=nil)
  ssl_context = OpenSSL::SSL::SSLContext.new
  set_cert(cert_path, ssl_context)
  set_key(key_path, ssl_context)
  set_root_ca(ca_path, ssl_context)
  # ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER unless ca_path.nil?
  ssl_context
end

#set_cert(cert_path = nil, ssl_context) ⇒ Object



30
31
32
33
34
# File 'lib/mqtt_rails/ssl_helper.rb', line 30

def set_cert(cert_path=nil, ssl_context)
  unless cert_path.nil?
    ssl_context.cert = OpenSSL::X509::Certificate.new(File.read(cert_path))
  end
end

#set_key(key_path = nil, ssl_context) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mqtt_rails/ssl_helper.rb', line 36

def set_key(key_path=nil, ssl_context)
  unless key_path.nil?
    return MQTT_ERR_SUCCESS if try_rsa_key(key_path, ssl_context) == MQTT_ERR_SUCCESS
    begin
      ssl_context.key = OpenSSL::PKey::EC.new(File.read(key_path))
      return MQTT_ERR_SUCCESS
    rescue OpenSSL::PKey::ECError
      raise NotSupportedEncryptionException.new("Could not support the type of the provided key (supported: RSA and EC)")
    end
  end
end

#set_root_ca(ca_path, ssl_context) ⇒ Object



57
58
59
# File 'lib/mqtt_rails/ssl_helper.rb', line 57

def set_root_ca(ca_path, ssl_context)
  ssl_context.ca_file = ca_path
end

#try_rsa_key(key_path, ssl_context) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/mqtt_rails/ssl_helper.rb', line 48

def try_rsa_key(key_path, ssl_context)
  begin
    ssl_context.key = OpenSSL::PKey::RSA.new(File.read(key_path))
    return MQTT_ERR_SUCCESS
  rescue OpenSSL::PKey::RSAError
    return MQTT_ERR_FAIL
  end
end