如何生成一个26个字符的十六进制字符串,该字符串等于106位和((二进制为(53个1-53个零))

亚当·格罗利

我正在寻找一种生成十六进制字符串的方法,该字符串等于106位,更具体地讲是在将每个十六进制char转换为二进制并加在一起之后的五十三个1和五十三个0。考虑到请求的参数,我想使其尽可能地随机。我将如何关注字符串的构造,以使其与我想要的方式一致?

例如:

(a8c05779f8934b14ce96f8aa93) =
(1010 1000 1100 0000 0101 0111 0111 1001 1111 1000 1001 0011 0100
 1011 0001 0100 1100 1110 1001 0110 1111 1000 1010 1010 1001 0011)
古法

您可以通过跟踪已经放置的位数来随机地将52个放入104位数字中,并计算下一位应该为1的概率。第一个数字始终具有1/2概率(52/104),然后第二个数字具有51/103或52/103概率,具体取决于第一个数字是什么,依此类推。

将这些位放在缓冲区中,并在缓冲区已满(四位)时,形成一个十六进制数字,可以将其添加到字符串中:

Dim rnd As New Random()
Dim bin As New StringBuilder()
Dim buf As Integer = 0, bufLen As Integer = 0, left As Integer = 52
For i As Integer = 104 To 1 Step -1
  buf <<= 1
  If rnd.Next(i) < left Then
    buf += 1
    left -= 1
  End If
  bufLen += 1
  If bufLen = 4 Then
    bin.Append("0123456789abcdef"(buf))
    bufLen = 0
    buf = 0
  End If
Next
Dim b As String = bin.ToString()

要使值为106位,请更改以下行:

Dim buf As Integer = 0, bufLen As Integer = 0, left As Integer = 53
For i As Integer = 106 To 1 Step -1

结果字符串仍然是26个字符,另外两个位在buf变量中。它之间的值0,并3可以使用它来创建27字符,但做到这一点。


要将22位哈希添加到字符串,可以使用如下代码:

bin.Append("048c"(buf))
Dim b As String = bin.ToString()

Dim m As New System.Security.Cryptography.SHA1Managed
Dim hash As Byte() = m.ComputeHash(Encoding.UTF8.GetBytes(b))

'replace first two bits in hash with bits from buf
hash(0) = CByte(hash(0) And &H3F Or (buf * 64))
'append 24 bits from hash
b = b.Substring(0, 26) + BitConverter.ToString(hash, 0, 3).Replace("-", String.Empty)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章