在使用TripleDESCryptoServiceProvider进行3DES加密的时候,使用16byte全F的密钥,抛出异常,提示弱密钥,但是该密钥是由上游厂商提供不能随意修改。因此只能想办法屏蔽掉弱密钥检查,即让isWeakKey方法返回false。
有2种解决方法:
一是重写TripleDESCryptoServiceProvider,虽然网上有现成的源码,但还是太麻烦。
二是利用.net的反射机制,手动创建ICryptoTransform实例,绕过.net自身的弱密钥检查,代码如下:
Public Function Encrypt3DES(ByVal strString As String, ByVal strKey As String) As String
'密文
Dim destStr As String = ""
'3DES加密对象
Dim DES As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
'初始向量
Dim Iv() As Byte = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
'密钥
Dim Key() As Byte = format.HexStringToByteArray(strKey)
Dim mi As MethodInfo = DES.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim param() As Object = {Key, CipherMode.CBC, Iv, DES.FeedbackSize, 0}
Dim DESEncrypt As ICryptoTransform = CType(mi.Invoke(DES, param), ICryptoTransform)
'明文的byte[]形式
Dim Buffer() As Byte = format.HexStringToByteArray(strString)
'加密得到密文的byte[]形式
Dim tmpStr() As Byte = DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)
'将密文转为可见字符
destStr = format.ByteArrayToHexString(tmpStr)
Encrypt3DES = destStr
End Function