首页 > 解决方案 > Base64 编码产生极长的结果

问题描述

以创建一个简单的 base64 编码为例。问题是在访问数据库中存储结果(编码字符串)时,返回的字符串是否大于数据库字段允许的值?最大字段长度为 255。为什么平均 8-15 个字符的字符串的结果会导致 350+ 个字符的编码结果。例如盐是"abcdefgh"

Public Function EncodePassword(ByVal pass As String, ByVal passwordFormat As Integer, ByVal salt As String) As String
    If passwordFormat = 0 Then Return pass
    Dim bIn As Byte() = Encoding.Unicode.GetBytes(pass)
    Dim bSalt As Byte() = Convert.FromBase64String(salt)
    Dim bAll As Byte() = New Byte(bSalt.Length + bIn.Length - 1) {}
    Dim bRet As Byte() = Nothing
    Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length)
    Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length)

    If passwordFormat = 1 Then
        Dim s As HashAlgorithm = HashAlgorithm.Create(_HashAlgorithmType)

        If s Is Nothing Then
            Throw New ProviderException("Could not create a hash algorithm")
        End If

        bRet = s.ComputeHash(bAll)
    Else
        bRet = EncryptPassword(bAll)
    End If

    Return Convert.ToBase64String(bRet)
End Function

标签: vb.netbase64

解决方案


结果是从数据库返回的字符串pass有尾随空格来填充 128 个字符的 DB 字段的长度(20 个字符的密码结尾有 108 个空格)。

固定与pass.TrimEnd()


推荐阅读