Skip to content

Commit

Permalink
Add back Util.hex2bin and .bin2hex
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri committed Aug 11, 2013
1 parent 0aa5db8 commit 44f5247
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/rbnacl/util.rb
Expand Up @@ -153,6 +153,24 @@ def verify16!(one, two)
check_length(two, 16, "Second message")
NaCl.crypto_verify_16(one, two)
end

# Hex encodes a message
#
# @param [String] bytes The bytes to encode
#
# @return [String] Tasty, tasty hexadecimal
def bin2hex(bytes)
bytes.to_s.unpack("H*").first
end

# Hex decodes a message
#
# @param [String] hex hex to decode.
#
# @return [String] crisp and clean bytes
def hex2bin(hex)
[hex.to_s].pack("H*")
end
end
end

14 changes: 14 additions & 0 deletions spec/rbnacl/util_spec.rb
Expand Up @@ -102,6 +102,7 @@
Crypto::Util.verify16(msg, long_msg).should be false
end
end

context "check_length" do
it "accepts strings of the correct length" do
expect { Crypto::Util.check_length("A"*4, 4, "Test String") }.not_to raise_error
Expand All @@ -116,4 +117,17 @@
expect { Crypto::Util.check_length(nil, 4, "Test String") }.to raise_error(Crypto::LengthError, "Test String was nil (Expected 4)")
end
end

context "hex encoding" do
let (:bytes) { [0xDE,0xAD,0xBE,0xEF].pack('c*') }
let (:hex) { "deadbeef" }

it "encodes to hex with bin2hex" do
Crypto::Util.bin2hex(bytes).should eq hex
end

it "decodes from hex with hex2bin" do
Crypto::Util.hex2bin(hex).should eq bytes
end
end
end

0 comments on commit 44f5247

Please sign in to comment.