将 RIJNDAEL 256 函数从 .Net 转换为 Python

Converting RIJNDAEL 256 function from .Net to Python

有人可以帮我转换这段代码吗?

我试图用这段代码使 RIJNDAEL256 发挥作用:

EncryptRJ256("lkirwf897+22#bbtrm8814z5qq=498j5", "741952hheeyy66#cs!9hjv887mxx7@8y", "A padded string to BLOCKSIZE length.")

Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String) As String
    Dim s As String = prm_text_to_encrypt
    Dim managed2 As New RijndaelManaged With {
    .Padding = PaddingMode.Zeros,
    .Mode = CipherMode.CBC,
    .BlockSize = 256
}
    Dim stream As New MemoryStream
    Dim stream2 As New CryptoStream(stream, managed2.CreateEncryptor(Encoding.ASCII.GetBytes(prm_key), Encoding.ASCII.GetBytes(prm_iv)), CryptoStreamMode.Write)
    Dim bytes As Byte() = Encoding.ASCII.GetBytes(s)
    stream2.Write(bytes, 0, bytes.Length)
    stream2.FlushFinalBlock()
    Return Convert.ToBase64String(stream.ToArray)
End Function

我需要加密字符串的输出是这样的:

Dv0Y/AFXdFMlDrcldFCu8v5o9zAlLNgyM+vO+PFeSrpO8Ve82mdUcc4rkzp9afDYc75NmkSd4mdflt38kceOdA==

A padded string to BLOCKSIZE length

我想到了这个,但输出无效。这可能是因为填充错误,但我不知道如何解决它:

from rijndael.cipher.crypt import new
from rijndael.cipher.blockcipher import MODE_CBC
import base64

PADDING = b'.'

def r_pad(payload, block_size=32):
    return payload + (block_size - len(payload) % block_size) * PADDING

KEY = 'lkirwf897+22#bbtrm8814z5qq=498j5'
IV = '741952hheeyy66#cs!9hjv887mxx7@8y'
plain_text = "A padded string to BLOCKSIZE length."

rjn = new(KEY, MODE_CBC, IV, blocksize=32)
encd = rjn.encrypt(r_pad(plain_text))
data = base64.b64encode(encd)
print(data)

rjn = new(KEY, MODE_CBC, IV, blocksize=32)
data = base64.b64decode(data)
decd = rjn.decrypt(r_pad(data))
print (decd)

这是输出:

Dv0Y/AFXdFMlDrcldFCu8v5o9zAlLNgyM+vO+PFeSrqWdzP1S1cumviFiEjNAjz5njnMMC9lfxsBl71x5y+xCw==

A padded string to BLOCKSIZE length.............................Å¿:è°⌐┘n┤«╞Px╜:æC┬♣╬Q┤▼«U_♦â☻ìr

我真傻!以下是解决我的问题的方法:

from rijndael.cipher.crypt import new
from rijndael.cipher.blockcipher import MODE_CBC
import base64

PADDING = b'\x00'

def pad(payload, block_size=32):
    return payload + (block_size - len(payload) % block_size) * PADDING

def un_pad(payload):
    return payload.replace(PADDING, '')

KEY = 'lkirwf897+22#bbtrm8814z5qq=498j5'
IV = '741952hheeyy66#cs!9hjv887mxx7@8y'
plain_text = "A padded string to BLOCKSIZE length."

rjn = new(KEY, MODE_CBC, IV, blocksize=32)
encd = rjn.encrypt(pad(plain_text))
data = base64.b64encode(encd)
print(data)

rjn = new(KEY, MODE_CBC, IV, blocksize=32)
data = base64.b64decode(data)
decd = rjn.decrypt(un_pad(data))
print (decd)