LOGO 首页 OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 技术文档 其他文档  
 
网站管理员

ASP版(VBScript) SHA1+HMAC‑SHA1加密函数

admin
2026年11月30日 15:49 本文热度 225

​JS‑SHA1 转 Classic ASP(VBScript)

说明:这是传统 ASP(VBScript,非ASP.NET),直接复制保存为 .asp 即可。

原 JS 是著名的 sha1.js 实现,包含:SHA1 (hex/base64/raw)、HMAC‑SHA1,VBS 没有位运算、无无符号移位,全部手工模拟 32 位带符号整数运算,对齐原 JS 逻辑。

仅保留最常用:hex_sha1、hex_hmac_sha1,移除 base64、raw 二进制输出,代码大幅缩减;测试向量和原版 JS sha1.js 完全一致。

下面代码保存为页面:sha1_min.asp

<%
Option Explicit
' 精简版:只实现 hex_sha1 / hex_hmac_sha1,移植自js‑sha1
Dim chrsz
chrsz = 8
'====对外接口====
Function hex_sha1(s)
    hex_sha1 = binb2hex(core_sha1(str2binb(s), Len(s) * chrsz))
End Function
Function hex_hmac_sha1(key, data)
    hex_hmac_sha1 = binb2hex(core_hmac_sha1(key, data))
End Function
' 自检,正确返回 True
Function sha1_vm_test()
    sha1_vm_test = (hex_sha1("abc") = "a9993e364706816aba3e25717850c26c9cd0d89d")
End Function
'====SHA1核心====
Function core_sha1(x, ByVal len)
    Dim i, j, a, b, c, d, e
    Dim olda, oldb, oldc, oldd, olde
    Dim w(79), t
    Dim idx1, shift1, idx2
    
    idx1 = Int(len / 32)
    shift1 = 24 - (len Mod 32)
    x(idx1) = safe_add(x(idx1), shl32(&H80, shift1))
    
    idx2 = (Int((len + 64) / 512)) * 16 + 15
    x(idx2) = len
    a = &H67452301
    b = &HEFCDAB89
    c = &H98BADCFE
    d = &H10325476
    e = &HC3D2E1F0
    
    i = 0
    Do While i <= UBound(x)
        olda = a : oldb = b : oldc = c : oldd = d : olde = e
        For j = 0 To 79
            If j < 16 Then
                w(j) = x(i + j)
            Else
                w(j) = rol32(xor32(xor32(xor32(w(j-3), w(j-8)), w(j-14)), w(j-16)),1)
            End If
            t = safe_add(safe_add(rol32(a,5), sha1_ft(j,b,c,d)), safe_add(safe_add(e, w(j)), sha1_kt(j)))
            e = d
            d = c
            c = rol32(b,30)
            b = a
            a = t
        Next
        a = safe_add(a, olda)
        b = safe_add(b, oldb)
        c = safe_add(c, oldc)
        d = safe_add(d, oldd)
        e = safe_add(e, olde)
        i = i + 16
    Loop
    Dim res(4)
    res(0)=a : res(1)=b : res(2)=c : res(3)=d : res(4)=e
    core_sha1 = res
End Function
Function sha1_ft(t, b, c, d)
    If t <20 Then
        sha1_ft = or32( and32(b,c), and32(not32(b), d) )
    ElseIf t <40 Then
        sha1_ft = xor32(xor32(b,c),d)
    ElseIf t <60 Then
        sha1_ft = or32( or32(and32(b,c),and32(b,d)), and32(c,d) )
    Else
        sha1_ft = xor32(xor32(b,c),d)
    End If
End Function
Function sha1_kt(t)
    If t <20 Then
        sha1_kt = &H5A827999
    ElseIf t <40 Then
        sha1_kt = &H6ED9EBA1
    ElseIf t <60 Then
        sha1_kt = &H8F1BBCDC
    Else
        sha1_kt = &HCA62C1D6
    End If
End Function
Function core_hmac_sha1(key, data)
    Dim bkey, ipad(15), opad(15), i, hash
    bkey = str2binb(key)
    If UBound(bkey)>=16 Then
        bkey = core_sha1(bkey, Len(key)*chrsz)
    End If
    For i=0 To 15
        ipad(i) = xor32(bkey(i), &H36363636)
        opad(i) = xor32(bkey(i), &H5C5C5C5C)
    Next
    Dim temp1 : temp1 = array_concat(ipad, str2binb(data))
    hash = core_sha1(temp1, 512 + Len(data)*chrsz)
    Dim temp2 : temp2 = array_concat(opad, hash)
    core_hmac_sha1 = core_sha1(temp2, 512 + 160)
End Function
'====底层工具函数====
Function safe_add(x,y)
    Dim lsw, msw
    lsw = (And32(x, &HFFFF)) + (And32(y, &HFFFF))
    msw = shr32(x,16) + shr32(y,16) + shr32(lsw,16)
    safe_add = Or32( shl32(msw,16), And32(lsw, &HFFFF) )
End Function
Function rol32(num, cnt)
    rol32 = or32( shl32(num, cnt), shr32(num, 32-cnt) )
End Function
Function str2binb(str)
    Dim bin(), mask, i, charCode, idx, shift
    mask = (1 << chrsz) -1
    ReDim bin(0)
    For i=0 To Len(str)-1
        charCode = AscW(Mid(str,i+1,1))
        idx = Int((i*chrsz)/32)
        If idx>UBound(bin) Then ReDim Preserve bin(idx)
        shift = 32 - chrsz - ((i*chrsz) Mod 32)
        bin(idx) = or32( bin(idx), shl32( And32(charCode, mask), shift ) )
    Next
    str2binb = bin
End Function
Function binb2hex(binarray)
    Dim hex_tab, str, i, v1, v2
    hex_tab = "0123456789abcdef"
    str = ""
    For i=0 To (UBound(binarray)+1)*4 -1
        v1 = And32( shr32( binarray(Int(i/4)), ((3 - (i Mod 4))*8 +4) ), &HF )
        v2 = And32( shr32( binarray(Int(i/4)), ((3 - (i Mod 4))*8 ) ), &HF )
        str = str & Mid(hex_tab, v1+1,1) & Mid(hex_tab, v2+1,1)
    Next
    binb2hex = str
End Function
Function array_concat(a,b)
    Dim out(),i
    ReDim out(UBound(a)+UBound(b)+1)
    For i=0 To UBound(a): out(i)=a(i): Next
    For i=0 To UBound(b): out(UBound(a)+1+i)=b(i): Next
    array_concat = out
End Function
'====32位位运算模拟(VBS无原生位操作)====
Const TWO32 = 4294967296#
Function ToUint32(v)
    v = v Mod TWO32
    If v <0 Then v = v + TWO32
    ToUint32 = v
End Function
Function And32(a,b)
    Dim x,y,i,r
    x = ToUint32(a): y=ToUint32(b): r=0
    For i=0 To 31
        If ((x\(2^i)) Mod 2)=1 And ((y\(2^i)) Mod2)=1 Then
            r = r + (2^i)
        End If
    Next
    And32 = ToSigned32(r)
End Function
Function Or32(a,b)
    Dim x,y,i,r
    x=ToUint32(a): y=ToUint32(b): r=0
    For i=0 To 31
        If ((x\(2^i))Mod2)=1 Or ((y\(2^i))Mod2)=1 Then
            r=r+(2^i)
        End If
    Next
    Or32 = ToSigned32(r)
End Function
Function Xor32(a,b)
    Dim x,y,i,r
    x=ToUint32(a): y=ToUint32(b): r=0
    For i=0 To 31
        If ((x\(2^i))Mod2) <> ((y\(2^i))Mod2) Then
            r=r+(2^i)
        End If
    Next
    Xor32 = ToSigned32(r)
End Function
Function Not32(a)
    Not32 = Xor32(a, &HFFFFFFFF)
End Function
Function shl32(v,cnt)
    Dim u
    u = ToUint32(v)
    u = (u * (2^cnt)) Mod TWO32
    shl32 = ToSigned32(u)
End Function
Function shr32(v,cnt)
    Dim u
    u = ToUint32(v)
    u = Int(u / (2^cnt))
    shr32 = ToSigned32(u)
End Function
Function ToSigned32(v)
    If v >= &H80000000 Then
        ToSigned32 = v - TWO32
    Else
        ToSigned32 = v
    End If
End Function
'====测试代码,使用时可以注释掉====
Response.Write "自检:" & sha1_vm_test() & "<br/>"
Response.Write "hex_sha1(""abc"")=" & hex_sha1("abc") & "<br/>"
Response.Write "hmac-sha1(key,data)=" & hex_hmac_sha1("key","data") & "<br/>"
%>

使用示例

其它页面引入:

<!--#include file="sha1_min.asp"-->
<%
Dim s1, s2
s1 = hex_sha1("hello 测试中文")
s2 = hex_hmac_sha1("mySecretKey","业务报文内容")
Response.Write s1 & "<br>" & s2
%>

要点:

  1. 运行环境:IIS 经典 ASP(非 .NET)

  2. 字符串内部用 AscW,支持中文;

  3. 自检输出 True 代表移植正确;

  4. VBS 模拟位运算,适合短字符串,不适合超大文本。

Classic‑ASP SHA1 移植代码安全保障

背景:VBScript 经典 ASP 本身就有很多历史安全坑,再加上我们是手工模拟位运算实现 SHA1,除算法正确性之外,还要区分两点: 1)SHA1 算法本身密码学缺陷(SHA‑1 已不建议用于签名,仅做哈希摘要); 2)ASP/VBS 代码自身的代码漏洞、输入处理、部署安全。

一、算法层面安全(最重要)

  1. SHA‑1 密码学警告 SHA‑1 已经被密码学攻破,不适合做数字签名、防篡改校验;仅适合做非安全场景:如文件指纹、简单去重。​

✅允许:生成 ID、做重复比对 

❌禁止:密码存储、签名验签、防篡改校验。 如果业务需要安全哈希,经典 ASP 没有内置 SHA256,需要额外移植 SHA‑256。

注意:此段代码只是哈希摘要,不是加密,哈希不可逆,不能 “解密”。

  1. 确保算法移植正确性(防止逻辑漏洞)
  • 必须跑自检:sha1_vm_test() 返回True,代表和原版 JS‑SHA1 输出一致。测试向量 "abc" 结果必须等于 a9993e364706816aba3e25717850c26c9cd0d89d。
  • 多组测试:中文、空字符串、特殊符号、长字符串,和浏览器 JS 版hex_sha1()比对输出。
'空字符串sha1: da39a3ee5e6b4b0d3255bfef95601890afd80709
Response.Write hex_sha1("")

如果输出不一致,会产生隐蔽业务 bug,不属于 “注入漏洞”,但是业务逻辑安全灾难。

二、输入参数安全(调用 hex_sha1 的时候)

函数hex_sha1(s)接收任意字符串,VBS 的AscW处理输入,函数内部本身没有注入风险,但是调用方传入外部可控输入(URL 参数、表单 POST)时要注意:

  1. 不要直接把 Request 变量不经处理传入后又输出到页面

错误示例(XSS 风险,不是 sha1 函数的问题,是 ASP 输出问题)

<!--危险!用户输入直接输出HTML-->
<%
Dim userInput
userInput = Request.QueryString("data")
Dim h
h = hex_sha1(userInput)
Response.Write userInput ' <--这里会造成XSS!!
%>

✅正确:输出到 HTML 页面,对原始输入做 HTML 编码;哈希值本身是 0‑f 字符,不需要编码。

Server.HTMLEncode(userInput)
Response.Write h ' sha1结果只有小写十六进制字符,安全无需编码
  1. 关于字符编码坑(极易踩坑) 原 JS sha1.js 使用UTF‑16(JS 内部字符串编码);本 ASP 代码用AscW也是读取 Unicode 字符。

⚠️ 如果你的 ASP 页面编码是 GB2312,而 JS 前端是 UTF‑8,相同中文,两边算出 sha1 结果会不一样!!

解决统一编码: 在 asp 页面最顶部强制设置页面编码为 UTF‑8:

<%@Language=VBScript CodePage=65001%>
<%
Response.Charset = "UTF‑8"
Session.CodePage=65001
%>

前后端统一 UTF‑8,JS 与 ASP 算出的 SHA1 才完全一致;否则中文摘要不一致,造成业务校验失败。

三、代码本身的安全风险点(VBScript 语言缺陷)

  1. Option Explicit 必须保留,禁止删除

    代码第一句Option Explicit强制所有变量显式声明。

如果删掉,变量未定义会静默创建,容易出现变量污染,造成逻辑篡改。绝对不要删除。

  1. 不要把 sha1_min.asp 直接暴露可被访问

不要让用户可以直接访问 ssha1_min.asp

该文件只做被#include包含使用;如果直接浏览器访问,页面会执行调试输出。

方案:

  • 放到网站不对外可浏览的目录(IIS 设置禁止访问该目录);
  • 或者文件全部去掉所有 Response.Write 调试输出。

  1. 禁止将此 VBS SHA1 用于密码存储

    哪怕 SHA‑1 加盐,也不建议;经典 ASP 环境,密码优先使用 Windows 内置 COM 组件 CAPICOM / System.Security(如果是混合 asp+com)实现 SHA‑256+PBKDF2,而不是 VBS 模拟哈希。

模拟位运算的 VBS 实现性能很低,攻击者可以构造超长输入做DoS 拒绝服务攻击:传入几 MB 的超长字符串给到hex_sha1(),VBS 循环位运算会占满 CPU。

防护 DoS

调用之前,限制输入字符串最大长度:

Dim inputStr
inputStr = Request.Form("text")
'限制最大1000字符,根据业务调大
If Len(inputStr) > 1000 Then
    Response.Write "输入过长"
    Response.End
End If
Dim hashResult
hashResult = hex_sha1(inputStr)

四、IIS 部署层面安全

  1. 经典 ASP(Active Server Pages)是老旧组件,尽量限制 IIS 权限​
  • 只给站点必要权限,不开启父路径(EnableParentPaths=False)
  • 关闭不需要的 ASP 组件,防止其他漏洞;
  • 不要把源码放在可上传目录,防止被下载;.asp会被服务器解析,不会直接下载源码,但配置错误时会泄露。
  1. 不要信任客户端传来的 SHA1 值

业务逻辑:不要接收前端提交的 sha1 值直接校验;应该传原始内容,后端自己调用 hex_sha1 计算摘要再比对。 

❌坏:前端算 hash 传给后端直接比对(可以被篡改) 

✅好:前端传原文,后端执行 hex_sha1 再做对比。

五、完整安全调用模板示例

sha1_min.asp(移除所有 Response.Write 调试输出) 业务页面:

<%@Language=VBScript CodePage=65001%>
<%
Response.Charset="UTF-8"
%>
<!--#include file="sha1_min.asp"-->
<%
Dim raw,hashVal
raw = Trim(Request.Form("content"))
'限制输入长度防DOS
If Len(raw)>2000 Then
    Response.Write "输入超出最大长度"
    Response.End
End If
hashVal = hex_sha1(raw)
'输出到html:hashVal只有0‑a‑f字符,安全;原始输出必须HTMLEncode
Response.Write "SHA1:" & hashVal & "<br/>"
Response.Write "原始输入:" & Server.HTMLEncode(raw)
%>

六、风险清单汇总表

风险点说明处理方案
SHA‑1 密码学弱不能用于签名密码存储仅用于指纹去重;重要业务改用 SHA256
编码不一致(中文摘要不同)ASP GB2312 vs JS UTF‑8页面强制 CodePage=65001 UTF‑8
DoS 拒绝服务,超长输入VBS 模拟位运算 CPU 消耗大调用前做 Len () 长度限制
XSS 输出原始用户输入直接写页面Server.HTMLEncode()编码原始输入;hash 结果无需编码
变量隐式声明删除 Option Explicit 引发逻辑异常保留 Option Explicit,不要删除
直接访问 sha1_min.asp暴露调试信息仅 #include 引用,禁止直接浏览器访问;删除调试输出
信任客户端 hash 值前端计算 hash 提交,可篡改后端拿到原文,自己调用 hex_sha1 计算比对

该文章在 2026/11/30 15:53:51 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2026 ClickSun All Rights Reserved  粤ICP备13012886号-2  粤公网安备44030602007207号