提醒:本页面将不再更新、维护或者支持,文章、评论所叙述内容存在时效性,涉及技术细节或者软件使用方面不保证能够完全有效可操作,请谨慎参考!

其实.NET Framework的一些库,ASP是可以直接借来用的,这点我在 《ASP/VBScript访问并使用.NET Framework对象》 文中已经做了简单的说明,今天正好又遇到一个借用.NET Framework实现某个特殊功能的例子。

在PHP中要计算文本的SHA-1其实很容易,直接使用sha1()这个函数就能轻松搞定了,但是在ASP中就杯具了,没有现成的函数,只能靠手写代码,包括md5()这些常用的哈希函数都要自己编码,好在已经有大牛帮我们写好代码了,我们只需要直接捡现成的用就可以了,比如说MD5就已经有不错的ASP/VBScript版本,关于不同语言的MD5实现可以 参考在这里 。好了,下面谈下比较棘手的SHA-1算法吧,你肯定说这个也有现成的ASP代码,是的,而且国内著名的ASP博客程序PJ-Blog已经内置了这种SHA-1算法了,那有什么好纠结的呢?PJ的SHA-1代码 源于这里 ,这个实现代码其实是JavaScript版本的,因为IIS的ASP技术默认支持VBScript和JavaScript/JScript两种脚本语言,所以我们可以直接拿来和VBScript混合使用。似乎这样也没有什么问题,但是对于ASP这种古老的技术而言,性能一直是其最大的瓶颈,而ASP性能建议上提到,不要混用两种脚本语言,也就是说混用VBScript和JScript会导致服务器缓存两个脚本解释引擎,而且会导致上下文切换的开销,所以性能上就有所损耗了,由于初始配置的IIS是把VBScript作为默认脚本语言,再加上JScript的对象模型,所以和JScript比起来VBScript可能性能上要好一点。

好吧,下面我们要做的是搞个VBScript版本的SHA-1,在这里我偷懒了点,求助了万能的谷歌,然后找到了一篇文章 《Replicating PHP’s sha1() in VBScript》 ,其中就提到了,借用.NET Framework的技术实现了VBScript版本的sha1,由于是通过Server.CreateObject实现的,所以代码比较简洁,性能上也应该说得过去,在这里我改写成类似PHP的sha1()函数:

Function sha1(instr)
  Dim asc, enc, bytes, outstr, pos
  'Borrow some objects from .NET (supported from 1.1 onwards)
  Set asc = Server.CreateObject("System.Text.UTF8Encoding")
  Set enc = Server.CreateObject( _
      "System.Security.Cryptography.SHA1CryptoServiceProvider")

  'Convert the string to a byte array and hash it
  bytes = asc.GetBytes_4(instr)
  bytes = enc.ComputeHash_2((bytes))

  outstr = ""

  'Convert the byte array to a hex string
  For pos = 1 To Lenb(bytes)
    outstr = outstr & LCase(Right("0" & Hex(Ascb(Midb(bytes, pos, 1))), 2))
  Next
  sha1 = outstr
  Set enc = Nothing
  Set asc = Nothing
End Function

然后大家可以直接调用了,注意,这个正常工作是有个前提的,对的,那就是服务器要装有.NET Framework,按作者原意是只要安装有.NET Framework 1.0就可以了,这个装机量应该不小了吧,大家可以试一试,如果你的服务不支持的话那只有暂时换用JS版的SHA1了,当然你也可以改写成md5版的代码:

Function md5(instr)
  Dim asc, enc, bytes, outstr, pos
  'Borrow some objects from .NET (supported from 1.1 onwards)
  Set asc = Server.CreateObject("System.Text.UTF8Encoding")
  Set enc = Server.CreateObject( _
      "System.Security.Cryptography.MD5CryptoServiceProvider")

  'Convert the string to a byte array and hash it
  bytes = asc.GetBytes_4(instr)
  bytes = enc.ComputeHash_2((bytes))

  outstr = ""

  'Convert the byte array to a hex string
  For pos = 1 To Lenb(bytes)
    outstr = outstr & LCase(Right("0" & Hex(Ascb(Midb(bytes, pos, 1))), 2))
  Next
  md5 = outstr
  Set enc = Nothing
  Set asc = Nothing
End Function

作者最后提到“Unfortunately, the same trick doesn’t work for the newer hash algorithms in .NET such as SHA256 or SHA512.”,看来更高级的SHA256 或者 SHA512是实现不了了。

有人 列出了VBScript/WSH可以使用的.NET组件列表 ,看来有时间可以好好研究下,找下有没有能拿来直接用的:

System.AccessViolationException System.AppDomainManager System.AppDomainSetup System.AppDomainUnloadedException System.ApplicationException System.ArgumentException System.ArgumentNullException System.ArgumentOutOfRangeException System.ArithmeticException System.ArrayTypeMismatchException System.BadImageFormatException System.CannotUnloadAppDomainException System.Collections.ArrayList System.Collections.CaseInsensitiveComparer System.Collections.CaseInsensitiveHashCodeProvider System.Collections.Generic.KeyNotFoundException System.Collections.Hashtable System.Collections.Queue System.Collections.SortedList System.Collections.Stack System.ContextMarshalException System.ContextStaticAttribute System.Data.SqlClient.SQLDebugging System.DataMisalignedException System.Diagnostics.Debugger System.Diagnostics.StackFrame System.Diagnostics.StackTrace System.Diagnostics.SymbolStore.SymDocumentType System.Diagnostics.SymbolStore.SymLanguageType System.Diagnostics.SymbolStore.SymLanguageVendor System.DivideByZeroException System.DllNotFoundException System.DuplicateWaitObjectException System.EnterpriseServices.CompensatingResourceManager.ClerkMonitor System.EnterpriseServices.CompensatingResourceManager.Compensator System.EnterpriseServices.Internal.AppDomainHelper System.EnterpriseServices.Internal.AssemblyLocator System.EnterpriseServices.Internal.ClientRemotingConfig System.EnterpriseServices.Internal.ClrObjectFactory System.EnterpriseServices.Internal.ComManagedImportUtil System.EnterpriseServices.Internal.ComSoapPublishError System.EnterpriseServices.Internal.GenerateMetadata System.EnterpriseServices.Internal.IISVirtualRoot System.EnterpriseServices.Internal.Publish System.EnterpriseServices.Internal.ServerWebConfig System.EnterpriseServices.Internal.SoapClientImport System.EnterpriseServices.Internal.SoapServerTlb System.EnterpriseServices.Internal.SoapServerVRoot System.EnterpriseServices.Internal.SoapUtility System.EnterpriseServices.RegistrationConfig System.EnterpriseServices.RegistrationHelper System.EntryPointNotFoundException System.EventArgs System.Exception System.ExecutionEngineException System.FieldAccessException System.FlagsAttribute System.FormatException System.Globalization.DateTimeFormatInfo System.Globalization.GregorianCalendar System.Globalization.HebrewCalendar System.Globalization.HijriCalendar System.Globalization.JapaneseCalendar System.Globalization.JulianCalendar System.Globalization.KoreanCalendar System.Globalization.NumberFormatInfo System.Globalization.StringInfo System.Globalization.TaiwanCalendar System.Globalization.ThaiBuddhistCalendar System.IndexOutOfRangeException System.InvalidCastException System.InvalidOperationException System.InvalidProgramException System.IO.DirectoryNotFoundException System.IO.DriveNotFoundException System.IO.EndOfStreamException System.IO.FileLoadException System.IO.FileNotFoundException System.IO.IOException System.IO.IsolatedStorage.IsolatedStorageException System.IO.MemoryStream System.IO.PathTooLongException System.IO.StringWriter System.MemberAccessException System.MethodAccessException System.MissingFieldException System.MissingMemberException System.MissingMethodException System.MTAThreadAttribute System.MulticastNotSupportedException System.NonSerializedAttribute System.NotFiniteNumberException System.NotImplementedException System.NotSupportedException System.NullReferenceException System.Object System.ObsoleteAttribute System.OperationCanceledException System.OutOfMemoryException System.OverflowException System.ParamArrayAttribute System.PlatformNotSupportedException System.Random System.RankException System.Reflection.AmbiguousMatchException System.Reflection.AssemblyName System.Reflection.CustomAttributeFormatException System.Reflection.InvalidFilterCriteriaException System.Reflection.ObfuscationAttribute System.Reflection.TargetException System.Reflection.TargetParameterCountException System.Resources.MissingManifestResourceException System.Resources.MissingSatelliteAssemblyException System.Runtime.CompilerServices.CallConvCdecl System.Runtime.CompilerServices.CallConvFastcall System.Runtime.CompilerServices.CallConvStdcall System.Runtime.CompilerServices.CallConvThiscall System.Runtime.CompilerServices.CompilerGlobalScopeAttribute System.Runtime.CompilerServices.DiscardableAttribute System.Runtime.CompilerServices.IDispatchConstantAttribute System.Runtime.CompilerServices.IUnknownConstantAttribute System.Runtime.CompilerServices.MethodImplAttribute System.Runtime.CompilerServices.NativeCppClassAttribute System.Runtime.Hosting.ApplicationActivator System.Runtime.InteropServices.ComConversionLossAttribute System.Runtime.InteropServices.COMException System.Runtime.InteropServices.ComImportAttribute System.Runtime.InteropServices.ComRegisterFunctionAttribute System.Runtime.InteropServices.ComUnregisterFunctionAttribute System.Runtime.InteropServices.ExternalException System.Runtime.InteropServices.InAttribute System.Runtime.InteropServices.InvalidComObjectException System.Runtime.InteropServices.InvalidOleVariantTypeException System.Runtime.InteropServices.MarshalDirectiveException System.Runtime.InteropServices.OptionalAttribute System.Runtime.InteropServices.OutAttribute System.Runtime.InteropServices.PreserveSigAttribute System.Runtime.InteropServices.RegistrationServices System.Runtime.InteropServices.RuntimeEnvironment System.Runtime.InteropServices.SafeArrayRankMismatchException System.Runtime.InteropServices.SafeArrayTypeMismatchException System.Runtime.InteropServices.SEHException System.Runtime.InteropServices.SetWin32ContextInIDispatchAttribute System.Runtime.InteropServices.TypeLibConverter System.Runtime.Remoting.Channels.ClientChannelSinkStack System.Runtime.Remoting.Channels.ServerChannelSinkStack System.Runtime.Remoting.Channels.TransportHeaders System.Runtime.Remoting.Contexts.Context System.Runtime.Remoting.Contexts.SynchronizationAttribute System.Runtime.Remoting.InternalRemotingServices System.Runtime.Remoting.Lifetime.ClientSponsor System.Runtime.Remoting.Lifetime.LifetimeServices System.Runtime.Remoting.Messaging.OneWayAttribute System.Runtime.Remoting.Messaging.RemotingSurrogateSelector System.Runtime.Remoting.Metadata.SoapAttribute System.Runtime.Remoting.Metadata.SoapFieldAttribute System.Runtime.Remoting.Metadata.SoapMethodAttribute System.Runtime.Remoting.Metadata.SoapParameterAttribute System.Runtime.Remoting.Metadata.SoapTypeAttribute System.Runtime.Remoting.Metadata.W3cXsd2001.SoapAnyUri System.Runtime.Remoting.Metadata.W3cXsd2001.SoapBase64Binary System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDate System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDay System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDuration System.Runtime.Remoting.Metadata.W3cXsd2001.SoapEntities System.Runtime.Remoting.Metadata.W3cXsd2001.SoapEntity System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary System.Runtime.Remoting.Metadata.W3cXsd2001.SoapId System.Runtime.Remoting.Metadata.W3cXsd2001.SoapInteger System.Runtime.Remoting.Metadata.W3cXsd2001.SoapLanguage System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth System.Runtime.Remoting.Metadata.W3cXsd2001.SoapName System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNcName System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNegativeInteger System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNmtoken System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNonNegativeInteger System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNonPositiveInteger System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNormalizedString System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNotation System.Runtime.Remoting.Metadata.W3cXsd2001.SoapPositiveInteger System.Runtime.Remoting.Metadata.W3cXsd2001.SoapQName System.Runtime.Remoting.Metadata.W3cXsd2001.SoapTime System.Runtime.Remoting.Metadata.W3cXsd2001.SoapToken System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYear System.Runtime.Remoting.ObjRef System.Runtime.Remoting.Proxies.ProxyAttribute System.Runtime.Remoting.RemotingException System.Runtime.Remoting.RemotingTimeoutException System.Runtime.Remoting.ServerException System.Runtime.Remoting.Services.EnterpriseServicesHelper System.Runtime.Remoting.Services.TrackingServices System.Runtime.Serialization.FormatterConverter System.Runtime.Serialization.Formatters.Binary.BinaryFormatter System.Runtime.Serialization.Formatters.InternalRM System.Runtime.Serialization.Formatters.SoapFault System.Runtime.Serialization.Formatters.SoapMessage System.Runtime.Serialization.ObjectIDGenerator System.Runtime.Serialization.OnDeserializedAttribute System.Runtime.Serialization.OnDeserializingAttribute System.Runtime.Serialization.OnSerializedAttribute System.Runtime.Serialization.OnSerializingAttribute System.Runtime.Serialization.OptionalFieldAttribute System.Runtime.Serialization.SerializationException System.Runtime.Serialization.SurrogateSelector System.Security.AllowPartiallyTrustedCallersAttribute System.Security.Cryptography.CryptoConfig System.Security.Cryptography.CryptographicException System.Security.Cryptography.CryptographicUnexpectedOperationException System.Security.Cryptography.CspParameters System.Security.Cryptography.DESCryptoServiceProvider System.Security.Cryptography.DSACryptoServiceProvider System.Security.Cryptography.DSASignatureDeformatter System.Security.Cryptography.DSASignatureFormatter System.Security.Cryptography.FromBase64Transform System.Security.Cryptography.HMACMD5 System.Security.Cryptography.HMACRIPEMD160 System.Security.Cryptography.HMACSHA1 System.Security.Cryptography.HMACSHA256 System.Security.Cryptography.HMACSHA384 System.Security.Cryptography.HMACSHA512 System.Security.Cryptography.MACTripleDES System.Security.Cryptography.MD5CryptoServiceProvider System.Security.Cryptography.PKCS1MaskGenerationMethod System.Security.Cryptography.RC2CryptoServiceProvider System.Security.Cryptography.RijndaelManaged System.Security.Cryptography.RIPEMD160Managed System.Security.Cryptography.RNGCryptoServiceProvider System.Security.Cryptography.RSACryptoServiceProvider System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter System.Security.Cryptography.RSAOAEPKeyExchangeFormatter System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter System.Security.Cryptography.RSAPKCS1SignatureDeformatter System.Security.Cryptography.RSAPKCS1SignatureFormatter System.Security.Cryptography.SHA1CryptoServiceProvider System.Security.Cryptography.SHA1Managed System.Security.Cryptography.SHA256Managed System.Security.Cryptography.SHA384Managed System.Security.Cryptography.SHA512Managed System.Security.Cryptography.SignatureDescription System.Security.Cryptography.ToBase64Transform System.Security.Cryptography.TripleDESCryptoServiceProvider System.Security.Cryptography.X509Certificates.X509Certificate System.Security.HostProtectionException System.Security.HostSecurityManager System.Security.Permissions.GacIdentityPermission System.Security.Permissions.HostProtectionAttribute System.Security.Policy.AllMembershipCondition System.Security.Policy.ApplicationDirectoryMembershipCondition System.Security.Policy.ApplicationTrust System.Security.Policy.Evidence System.Security.Policy.GacInstalled System.Security.Policy.GacMembershipCondition System.Security.Policy.PolicyException System.Security.Policy.TrustManagerContext System.Security.SecurityException System.Security.SuppressUnmanagedCodeSecurityAttribute System.Security.UnverifiableCodeAttribute System.Security.VerificationException System.Security.XmlSyntaxException System.SerializableAttribute System.StackOverflowException System.STAThreadAttribute System.SystemException System.Text.ASCIIEncoding System.Text.StringBuilder System.Text.UnicodeEncoding System.Text.UTF7Encoding System.Text.UTF8Encoding System.Threading.Mutex System.Threading.Overlapped System.Threading.ReaderWriterLock System.Threading.SynchronizationLockException System.Threading.ThreadInterruptedException System.Threading.ThreadStateException System.ThreadStaticAttribute System.TimeoutException System.TypeLoadException System.TypeUnloadedException System.UnauthorizedAccessException System.Version

参考文档 《.NET COM+ Interop Component with Classic ASP》