Skip to content

Instantly share code, notes, and snippets.

@declan
Last active March 30, 2016 21:40
Show Gist options
  • Save declan/e77c8e96b7f19e250604ce5b3ae275f7 to your computer and use it in GitHub Desktop.
Save declan/e77c8e96b7f19e250604ce5b3ae275f7 to your computer and use it in GitHub Desktop.
PBKDF2-HMAC test cases
# This file prints out the test cases for PBKDF2-HMAC-SHA1
# listed in RFC 6070, and similar test cases using SHA256
# listed in this StackOverflow thread:
# http://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors?rq=1
#
#
require 'openssl'
SHA1_TEST_VECTORS = [
{
password: 'password',
salt: 'salt',
c: 1,
key_len: 20
},
{
password: 'password',
salt: 'salt',
c: 2,
key_len: 20
},
{
password: 'password',
salt: 'salt',
c: 4096,
key_len: 20
},
{
password: 'password',
salt: 'salt',
c: 16777216,
key_len: 20
},
{
password: 'passwordPASSWORDpassword',
salt: 'saltSALTsaltSALTsaltSALTsaltSALTsalt',
c: 4096,
key_len: 25
},
{
password: "pass\0word",
salt: "sa\0lt",
c: 4096,
key_len: 16
}
]
SHA256_TEST_VECTORS = [
{
password: 'password',
salt: 'salt',
c: 1,
key_len: 32
},
{
password: 'password',
salt: 'salt',
c: 2,
key_len: 32
},
{
password: 'password',
salt: 'salt',
c: 4096,
key_len: 32
},
{
password: 'password',
salt: 'salt',
c: 16777216,
key_len: 32
},
{
password: 'passwordPASSWORDpassword',
salt: 'saltSALTsaltSALTsaltSALTsaltSALTsalt',
c: 4096,
key_len: 40
},
{
password: "pass\0word",
salt: "sa\0lt",
c: 4096,
key_len: 16
}
]
def test_with_digest(example, digest)
puts "\nInput:"
puts " P = \"#{example[:password]}\""
puts " S = \"#{example[:salt]}\""
puts " c = #{example[:c].to_s}"
puts " dkLen = #{example[:key_len].to_s}"
puts ""
puts "Output:"
# This is what we're actually testing.
# Compute the Derived Key using the OpenSSL library.
#
# The last parameter, "digest", is where we say whether to use
# SHA1 or SHA256.
#
dk = OpenSSL::PKCS5.pbkdf2_hmac(example[:password], example[:salt], example[:c], example[:key_len], digest)
# Now we're just formatting the Derived Key for printing
# so it looks like the test output in RFC 6070
#
dk_hex_formatted = dk.unpack('H*').first
dk_hex_formatted.split(/(\w{2})/).select { |s| s.length > 0 }.each_slice(8) { |a| puts ' ' + a.join(' ') }
return dk_hex_formatted
end
puts "\nTesting PBKDF2-HMAC-SHA1"
SHA1_TEST_VECTORS.each do |example|
test_with_digest(example, OpenSSL::Digest::SHA1.new)
end
puts "\nTesting PBKDF2-HMAC-SHA2"
SHA256_TEST_VECTORS.each do |example|
test_with_digest(example, OpenSSL::Digest::SHA256.new)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment