Commit f85e1f1

mokha <mo@mokhan.ca>
2019-01-21 23:26:19
encrypt symmetric key
1 parent 3c4ebdb
Changed files (3)
lib/xml/kit/templates/encrypted_key.builder
@@ -1,3 +1,6 @@
 xml.EncryptedKey Id: id, xmlns: ::Xml::Kit::Namespaces::XMLENC do
-
+  xml.EncryptionMethod Algorithm: algorithm
+  xml.CipherData do
+    xml.CipherValue cipher_value
+  end
 end
lib/xml/kit/encrypted_key.rb
@@ -5,10 +5,18 @@ module Xml
     class EncryptedKey
       include ::Xml::Kit::Templatable
 
-      attr_reader :id
+      attr_reader :id, :algorithm
+      attr_reader :public_key, :key
 
-      def initialize(id:)
+      def initialize(id:, public_key:, key:, algorithm: ::Xml::Kit::Crypto::RsaCipher::ALGORITHM)
         @id = id
+        @algorithm = algorithm
+        @public_key = public_key
+        @key = key
+      end
+
+      def cipher_value
+        Base64.strict_encode64(public_key.public_encrypt(key))
       end
     end
   end
spec/xml/kit/encrypted_key_spec.rb
@@ -1,15 +1,23 @@
 RSpec.describe ::Xml::Kit::EncryptedKey do
   describe "#to_xml" do
-    subject { described_class.new(id: id) }
+    subject { described_class.new(id: id, algorithm: algorithm, public_key: public_key, key: symmetric_key) }
+    let(:algorithm) { ::Xml::Kit::Crypto::RsaCipher::ALGORITHM }
     let(:id) { ::Xml::Kit::Id.generate }
+    let(:private_key) { OpenSSL::PKey::RSA.new(2048) }
+    let(:public_key) { private_key.public_key }
+    let(:expected_cipher_value) { Base64.strict_encode64(public_key.public_encrypt(symmetric_key)) }
+    let(:symmetric_key) { SecureRandom.hex(32) }
     let(:result) { Hash.from_xml(subject.to_xml) }
 
     before do
-      puts subject.to_xml
+      puts subject.to_xml(pretty: true)
     end
 
     specify { expect(result.key?('EncryptedKey')).to be_present }
     specify { expect(result['EncryptedKey']['Id']).to eql(id) }
     specify { expect(result['EncryptedKey']['xmlns']).to eql(::Xml::Kit::Namespaces::XMLENC) }
+    specify { expect(result['EncryptedKey']['EncryptionMethod']['Algorithm']).to be_present }
+    specify { expect(result['EncryptedKey']['CipherData']['CipherValue']).to be_present }
+    specify { expect(private_key.private_decrypt(Base64.decode64(result['EncryptedKey']['CipherData']['CipherValue']))).to eql(symmetric_key) }
   end
 end