VBA 中的 HMAC-SHA1 URL 加密会产生不正确的输出

作者:编程家 分类: vba 时间:2025-10-23

自然语言生成的文章如下:

在VBA中,加密是一项常见的操作,而HMAC-SHA1算法是其中一种常用的加密方式。然而,使用VBA中的HMAC-SHA1 URL加密时,我们可能会遇到一个问题:输出结果不正确。本文将探讨这个问题,并提供解决方案。

在VBA中使用HMAC-SHA1 URL加密时,我们通常会使用一个函数来实现。以下是一个例子:

vba

Function HMACSHA1_URL(ByVal key As String, ByVal message As String) As String

Dim keyBytes() As Byte

keyBytes = StrConv(key, vbFromUnicode)

Dim messageBytes() As Byte

messageBytes = StrConv(message, vbFromUnicode)

Dim hmacSHA1 As Object

Set hmacSHA1 = CreateObject("System.Security.Cryptography.HMACSHA1")

hmacSHA1.key = keyBytes

Dim hashBytes() As Byte

hashBytes = hmacSHA1.ComputeHash_2((messageBytes))

HMACSHA1_URL = Convert.ToBase64String(hashBytes)

End Function

上述代码定义了一个名为HMACSHA1_URL的函数,它接受一个秘钥(key)和一个消息(message)作为输入,并返回一个加密后的字符串。

然而,使用这个函数进行HMAC-SHA1 URL加密时,我们可能会发现输出结果并不正确。这是因为在VBA中,字符串的编码方式可能会导致问题。

为了解决这个问题,我们可以使用"ADODB.Stream"对象来确保正确的编码。以下是修改后的函数代码:

vba

Function HMACSHA1_URL(ByVal key As String, ByVal message As String) As String

Dim keyBytes() As Byte

keyBytes = StrConv(key, vbFromUnicode)

Dim messageBytes() As Byte

messageBytes = StrConv(message, vbFromUnicode)

Dim hmacSHA1 As Object

Set hmacSHA1 = CreateObject("System.Security.Cryptography.HMACSHA1")

hmacSHA1.key = keyBytes

Dim hashBytes() As Byte

hashBytes = hmacSHA1.ComputeHash_2((messageBytes))

Dim stream As Object

Set stream = CreateObject("ADODB.Stream")

stream.Type = 1 ' adTypeBinary

stream.Open

stream.Write hashBytes

stream.Position = 0

Dim base64Encoded As String

base64Encoded = stream.ReadText(-1)

stream.Close

HMACSHA1_URL = base64Encoded

End Function

通过使用"ADODB.Stream"对象,我们可以确保字符串的正确编码,并获得正确的HMAC-SHA1 URL加密结果。

案例代码:

假设我们有一个秘钥为"mykey",消息为"Hello World"。我们可以使用上述修改后的函数进行HMAC-SHA1 URL加密:

vba

Sub Example()

Dim key As String

key = "mykey"

Dim message As String

message = "Hello World"

Dim encryptedText As String

encryptedText = HMACSHA1_URL(key, message)

MsgBox encryptedText

End Sub

运行上述代码,我们将会得到正确的HMAC-SHA1 URL加密结果,可以用于安全传输或其他需要加密的应用中。

通过修改函数代码,使用"ADODB.Stream"对象来确保正确的编码,我们解决了VBA中HMAC-SHA1 URL加密产生不正确输出的问题。这个修改后的函数可以用于各种加密场景,确保数据的安全性。