【问题标题】:How to determine whether a byte array contains hashed data如何判断一个字节数组是否包含散列数据
【发布时间】:2014-01-22 10:06:12
【问题描述】:

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

【问题讨论】:

  • 您命名的函数不是一种加密形式,而是一种基于密码的密钥派生函数。如果数据前没有特定标识符等(这是相当特定于实现的),则此函数的输出将看起来像随机数据。如果数据看起来不是随机的,则可能没有由此生成散列;如果是这样,您将无法确定随机数据的来源(除非您可以猜到应该由该函数进行哈希处理的密码)。
  • 好的,明白了。谢谢。
  • 哦,我忘了一件事:SHA-1 哈希(以及 PBKDF2WithHmacSHA1 的输出)是 160 位长。如果数组不完全由 20 个字节组成(并且没有任何额外的前置或附加到它),您可以确定它不是这样的散列。

标签: encryption hmacsha1 pbkdf2


【解决方案1】:

下面是我在 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 实例是否经过散列,我只需检查整个缓冲区的长度——完整的源代码可用here .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2020-01-22
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多