Commit 1c38f34

mo <mo@mokhan.ca>
2017-12-11 21:54:45
move xml_encryption to a separate file.
1 parent afc8d7c
lib/saml/kit/builders/templates/response.builder
@@ -4,7 +4,7 @@ xml.Response response_options do
   xml.Status do
     xml.StatusCode Value: status_code
   end
-  with_encryption(xml) do |xml|
+  encryption_for(xml: xml) do |xml|
     xml.Assertion(assertion_options) do
       xml.Issuer issuer
       signature_for(reference_id: reference_id, xml: xml) unless encrypt
lib/saml/kit/builders/response.rb
@@ -1,19 +1,5 @@
 module Saml
   module Kit
-    class XmlEncryption
-      attr_reader :public_key
-      attr_reader :key, :iv, :encrypted
-
-      def initialize(raw_xml, public_key)
-        @public_key = public_key
-        cipher = OpenSSL::Cipher.new('AES-256-CBC')
-        cipher.encrypt
-        @key = cipher.random_key
-        @iv = cipher.random_iv
-        @encrypted = cipher.update(raw_xml) + cipher.final
-      end
-    end
-
     module Builders
       class Response
         include Templatable
@@ -51,17 +37,8 @@ module Saml
 
         private
 
-        def with_encryption(xml)
-          if encrypt
-            temp = ::Builder::XmlMarkup.new
-            yield temp
-
-            encryption_certificate = request.provider.encryption_certificates.first
-            xml_encryption = XmlEncryption.new(temp.target!, encryption_certificate.public_key)
-            Template.new(xml_encryption).to_xml(xml: xml)
-          else
-            yield xml
-          end
+        def encryption_certificate
+          request.provider.encryption_certificates.first
         end
 
         def destination_for(request)
lib/saml/kit/templatable.rb
@@ -74,6 +74,17 @@ module Saml
       def signatures
         @signatures ||= Saml::Kit::Signatures.new(configuration: configuration, sign: sign)
       end
+
+      def encryption_for(xml:)
+        if encrypt && encryption_certificate
+          temp = ::Builder::XmlMarkup.new
+          yield temp
+          xml_encryption = XmlEncryption.new(temp.target!, encryption_certificate.public_key)
+          Template.new(xml_encryption).to_xml(xml: xml)
+        else
+          yield xml
+        end
+      end
     end
   end
 end
lib/saml/kit/xml_encryption.rb
@@ -0,0 +1,18 @@
+module Saml
+  module Kit
+    class XmlEncryption
+      attr_reader :public_key
+      attr_reader :key, :iv, :encrypted
+
+      def initialize(raw_xml, public_key)
+        @public_key = public_key
+        cipher = OpenSSL::Cipher.new('AES-256-CBC')
+        cipher.encrypt
+        @key = cipher.random_key
+        @iv = cipher.random_iv
+        @encrypted = cipher.update(raw_xml) + cipher.final
+      end
+    end
+  end
+end
+
lib/saml/kit.rb
@@ -47,6 +47,7 @@ require "saml/kit/signature"
 require "saml/kit/template"
 require "saml/kit/xml"
 require "saml/kit/xml_decryption"
+require "saml/kit/xml_encryption"
 
 I18n.load_path += Dir[File.expand_path("kit/locales/*.yml", File.dirname(__FILE__))]