以下是vb.net的代码段。我想将它转换为python。我使用了hashlib,hmac和pyDes,但是没有一个产生与vb程序相同的结果。有什么建议。?这是我第一次处理加密。请帮我解决这个问题.. 代码:
Imports Microsoft.VisualBasic.CompilerServices
Imports System
Imports System.Diagnostics
Imports System.Security.Cryptography
Imports System.Text
Namespace _Cargo
Public Class Crypto
Private Shared DES As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
Private Shared MD5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
<DebuggerNonUserCode()>
Public Sub New()
End Sub
Public Shared Function MD5Hash(value As String) As Byte()
Return Crypto.MD5.ComputeHash(Encoding.ASCII.GetBytes(value))
End Function
Public Shared Function Encrypt(stringToEncrypt As String) As String
Crypto.DES.Key = Crypto.MD5Hash("L6#F&,q2$xLx")
Crypto.DES.Mode = CipherMode.ECB
Dim bytes As Byte() = Encoding.ASCII.GetBytes(stringToEncrypt)
Return Convert.ToBase64String(Crypto.DES.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length))
End Function
Public Shared Function Decrypt(encryptedString As String) As String
Dim result As String
Try
Crypto.DES.Key = Crypto.MD5Hash("L6#F&,q2$xLx")
Crypto.DES.Mode = CipherMode.ECB
Dim array As Byte() = Convert.FromBase64String(encryptedString)
result = Encoding.ASCII.GetString(Crypto.DES.CreateDecryptor().TransformFinalBlock(array, 0, array.Length))
Return result
Catch expr_4D As Exception
ProjectData.SetProjectError(expr_4D)
ProjectData.ClearProjectError()
End Try
result = Nothing
Return result
End Function
End Class
End Namespace
答案 0 :(得分:1)
查看以下代码段
DES的签名
pyDes.des(key, [mode], [IV], [pad], [padmode])
from pyDes import *
data = "Please encrypt my data"
k = des("DESCRYPT", ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
print "Encrypted: %r" % d
print "Decrypted: %r" % k.decrypt(d)
<强>更新强>
我已将vb.net代码转换为python并且工作正常
from pyDes import *
import hashlib
import base64
key = hashlib.md5("L6#F&,q2$xLx").digest()
data = "I love security"
k = triple_des(key, ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
base64Encrypted= base64.b64encode(d)
print "Encrypted: %r" % d
base64Decrypted= base64.b64decode(base64Encrypted)
print "Decrypted: %r" % k.decrypt(base64Decrypted)
答案 1 :(得分:0)
您可以使用Crypto库,非常方便所有与加密相关的内容
from Crypto.Cipher import DES
from Crypto.Hash import MD5
from Crypto import Random
def encrypt(string, key):
hash = MD5.new(key).digest()
iv = Random.new().read(DES.block_size)
cipher = DES.new(hash, DES.MODE_ECB, iv)
return iv + cipher.encrypt(string)