首页 > 解决方案 > 如何在 F# 中为 ShipHash 的键创建一个 16 字节的数组?

问题描述

我正在处理需要散列值的代码。SipHash 似乎是一个不错的选择。

  let getSipHashValue (buffer:byte []) (key:byte []) =
    match key.GetLength(0) with
    | 16  -> SipHash24.Hash64(buffer, key)
    | _   -> uint64(0)

有没有办法将密钥填充到 16 个字节并确保它有效?

我可以获得确切长度的单词作为键,但我希望能够使用任何单词(小于 16 个字节)并且只使用一些填充。

open System
open System.Text

let testKey : byte [] =
  Encoding.UTF8.GetBytes "accumulativeness"

Console.WriteLine("Length: {0}", testKey.GetLength(0))

有没有办法在 F# 中做到这一点?

标签: hashf#

解决方案


我想我明白了:

open System
open System.Text

let rec getPaddedBytes (s:string) =
  let b = Encoding.UTF8.GetBytes s
  match b.GetLength(0) with
  | 16 -> b
  | x when x < 16 -> getPaddedBytes (s + "0")
  | _ -> b[0..15]

Console.WriteLine("Length: {0}", testKey.GetLength(0))

let testBytes = getPaddedBytes "accum"
let testString = Encoding.UTF8.GetString testBytes

Console.WriteLine("X: {0}", testString)

我需要修复获取前 16 个字节的问题。不确定该语法。


推荐阅读