我使用AesCryptoServiceProvider来使用AES执行加密和解密。 加密似乎有效,但解密会抛出一个异常,说“填充无效,无法删除”。
这是我的代码:
Public Function AESEnc(ByVal plain As String, ByVal key As String, ByVal iv As String) As AesResult
Dim ciphertext As String
Dim k(31) As Byte
Dim v(15) As Byte
Dim ret As AesResult
Dim pBytes As Byte() = StrToByteArray(plain)
Dim cipher As New AesCryptoServiceProvider()
Dim enc As ICryptoTransform
Dim ms As New MemoryStream
Dim cs As CryptoStream
k = StrToByteArray(key)
v = HexStringByteArrayConverter.HexStringToBytes(iv)
cipher.Mode = CipherMode.CFB
cipher.Padding = PaddingMode.PKCS7
enc = cipher.CreateEncryptor(k, v)
cs = New CryptoStream(ms, enc, CryptoStreamMode.Write)
cs.Write(pBytes, 0, pBytes.Length)
cs.FlushFinalBlock()
cs.Close()
ciphertext = HexStringByteArrayConverter.BytesToHexString(ms.ToArray())
ret.data = ciphertext
ret.iv = v
ret.key = k
Return ret
End Function 'AESEnc
Public Function AESDec(ByVal ciphertext As String, ByVal key As String, ByVal iv As String) As AesResult
Dim plaintext As String
Dim k(31) As Byte
Dim v(15) As Byte
Dim ret As AesResult
Dim pBytes As Byte() = StrToByteArray(ciphertext)
Dim cipher As New AesCryptoServiceProvider()
Dim dec As ICryptoTransform
Dim ms As New MemoryStream
Dim cs As CryptoStream
k = StrToByteArray(key)
v = HexStringByteArrayConverter.HexStringToBytes(iv)
cipher.Mode = CipherMode.CFB
cipher.Padding = PaddingMode.PKCS7
dec = cipher.CreateDecryptor(k, v)
cs = New CryptoStream(ms, dec, CryptoStreamMode.Write)
cs.Write(pBytes, 0, pBytes.Length)
cs.FlushFinalBlock()
cs.Close()
plaintext = ByteArrayToString(ms.ToArray())
ret.data = plaintext
ret.iv = v
ret.key = k
Return ret
End Function 'AESDec