0

大家好,我正在尝试将 Java 代码迁移到 VB,现在我需要复制 DES 加密,但我在这部分遇到了问题。

我承认我从大学开始就没有做过加密。

这使用 MD5 加密密钥,并将其发送到 DES 加密函数,似乎我得到了错误的线索,密钥必须是 8 位密钥,而我正在发送 16 位长度的密钥。

Dim MD5 As New MD5CryptoServiceProvider()
        Dim dataHash() As Byte = MD5.ComputeHash(Encoding.UTF8.GetBytes(challenge + password))
        Dim sb As New StringBuilder
        Dim b As Byte
        For Each b In dataHash
            sb.Append(b.ToString("x2").ToLower())
        Next
        Dim md5Key As String = sb.ToString
        ''Dim md5Key As String = digestUtils.md5Hex(challenge + password)
        Dim geoEncrypt As New GeoEncriptamiento
        Dim challengeAnswer As String = geoEncrypt.EncryptFile(challenge, md5Key)

这是进行加密的代码

Function EncryptFile(ByVal esquema As String, ByVal llave As String) As String

    Dim DES As New DESCryptoServiceProvider()

    'Establecer la clave secreta para el algoritmo DES.
    'Se necesita una clave de 64 bits y IV para este proveedor
    DES.Key = UTF8Encoding.UTF8.GetBytes(llave)
    DES.IV = UTF8Encoding.UTF8.GetBytes(llave)
    Try
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(esquema)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(MS, DES.CreateEncryptor(DES.Key, DES.IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return "Error"
    End Try
End Function

错误是当我尝试将 MD5 解析为 DES.Key

4

2 回答 2

1

我会检查您对 UTF8Encoding.UTF8.GetBytes(llave) 的使用这可能会将传入的 16 字节密钥转换为 createencryptor 不期望的格式。

createencryptor 期望看到一个与 BLOCKSIZE 大小相同的密钥,根据文档,它是 64 位或 8 个字节。

由于这个循环 For Each b In dataHash sb.Append(b.ToString("x2").ToLower()) Next

另请注意,computehash 函数返回 16 字节数组,而不是 8 字节“MD5 类的 ComputeHash 方法将哈希返回为 16 字节数组。请注意,某些 MD5 实现会生成 32 个字符的十六进制格式的哈希。要与此类实现互操作,请将 ComputeHash 方法的返回值格式化为十六进制值。”

看起来您要么需要使用不同的散列,要么只使用 16 字节散列的一部分。

于 2010-10-07T21:12:51.207 回答
0

解决方案很简单,首先我们需要将字符串切割成 8 个位置(它可以获得的 8 个字节),最后让它兼容添加 cyphermode。这是代码

   Function EncryptFile(ByVal esquema As String, ByVal llave As String) As String
    Dim DES As New DESCryptoServiceProvider()
    DES.Mode = CipherMode.ECB
    Dim md5 As New MD5CryptoServiceProvider()
    DES.Key = UTF8Encoding.UTF8.GetBytes(llave.Substring(0, 8))
    DES.IV = UTF8Encoding.UTF8.GetBytes(llave.Substring(0, 8))
    Try
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(esquema)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, DES.CreateEncryptor(DES.Key, DES.IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return "Error"
    End Try
End Function
于 2010-10-08T17:52:06.473 回答