From 614e1fdc42ffe01afaf5fee0389af92fcd8f3ee9 Mon Sep 17 00:00:00 2001 From: Arto Bendiken Date: Mon, 6 Sep 2010 10:32:24 +0200 Subject: [PATCH] Implemented an RSA::KeyPair#to_hash method. --- lib/rsa/key_pair.rb | 11 +++++++++++ spec/key_pair_spec.rb | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/rsa/key_pair.rb b/lib/rsa/key_pair.rb index 4e17380..e08f2db 100644 --- a/lib/rsa/key_pair.rb +++ b/lib/rsa/key_pair.rb @@ -87,6 +87,17 @@ def modulus end alias_method :n, :modulus + ## + # Returns a hash table representation of this key pair. + # + # @example + # key_pair.to_hash #=> {:n => ..., :d => ..., :e => ...} + # + # @return [Hash] + def to_hash + {:n => modulus, :d => private_key ? private_key.exponent : nil, :e => public_key ? public_key.exponent : nil} + end + ## # Encrypts the given `plaintext` using the public key from this key # pair. diff --git a/spec/key_pair_spec.rb b/spec/key_pair_spec.rb index 075516c..75890a7 100644 --- a/spec/key_pair_spec.rb +++ b/spec/key_pair_spec.rb @@ -61,6 +61,20 @@ end end + context "#to_hash" do + it "returns a hash" do + @key_pair.to_hash.should be_a(Hash) + end + + it "returns a hash with the correct keys" do + [:n, :d, :e].each { |key| @key_pair.to_hash.should have_key(key) } + end + + it "returns a hash with the correct values" do + @key_pair.to_hash.should == {:n => @n, :d => @d, :e => @e} + end + end + context "#encrypt(Integer)" do it "accepts an integer argument" do lambda { @key_pair.encrypt(42) }.should_not raise_error(ArgumentError)