Is it possible to determine whether a byte array contains data hashed with PBKDF2WithHmacSHA1? Is there a pattern that could help?
Here below is how I solved the issue in Scala:
class Password(value: String, salt: Option[String]) {
private final val IterationCount = 2048
private final val KeyLength = 256
private final val SaltLength = KeyLength / 8
...
def hash = {
val zalt = if (salt.isDefined)
salt.get.getBytes(DefaultCharset)
else
SecureRandom.getInstance("SHA1PRNG").generateSeed(SaltLength)
val secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val secretKey = secretKeyFactory.generateSecret(
new PBEKeySpec(value.toCharArray, zalt, IterationCount, KeyLength)
)
val byteBuffer = ByteBuffer.allocate(2 + KeyLength)
byteBuffer.putShort(KeyLength)
byteBuffer.put(secretKey.getEncoded)
new Password(
Base64.encodeBase64String(byteBuffer.array),
Some(new String(zalt, DefaultCharset))
)
}
def isHashed = Base64.decodeBase64(value).length > KeyLength
}
The length of the key is prepended to the encoded hash... and to determine whether or not the current Password
instance is hashed I just check the length of the whole buffer – the complete source code is available here.