0

是否可以确定字节数组是否包含使用 PBKDF2WithHmacSHA1 散列的数据?有没有可以提供帮助的模式?

4

1 回答 1

0

下面是我在 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
}

密钥的长度被添加到编码散列之前......并且要确定当前Password实例是否经过散列,我只需检查整个缓冲区的长度 - 完整的源代码可在此处获得。

于 2014-01-04T22:11:03.310 回答