Zdravím, potřebuji pomocí AES šifrovat soubory, vzal jsem kód z http://www.obviex.com/samples/Encryption..., upravil si ho aby místo text bral a vyhazoval pole bytů. Funguje dobře, jenom mám problém, že dešifrovaná data nejsou stejná jako ta původní - na konci se objeví několik dalších nulových bajtů - konkrétně nový soubor má 40177, což je taky divný, protože by bajty měli být doplněny na 16, tady 1 přebývá... Zkoušel jsem všechny možnosti naatavení Padding, ale bez úspěchu. Je nějaké řešení jak tomu zabránit kromě oříznutí konce souboru?
Function Encrypt(ByVal input As Byte(), _
ByVal key As Byte(), _
ByVal iv As Byte()) _
As Byte()
Dim symmetricKey As New Security.Cryptography.AesManaged
symmetricKey.Mode = Security.Cryptography.CipherMode.CBC
Dim encryptor As Security.Cryptography.ICryptoTransform
encryptor = symmetricKey.CreateEncryptor(key, iv)
' Define memory stream which will be used to hold encrypted data.
Dim memoryStream As New IO.MemoryStream
Dim cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
encryptor, _
Security.Cryptography.CryptoStreamMode.Write)
' Start encrypting.
cryptoStream.Write(input, 0, input.Length)
' Finish encrypting.
cryptoStream.FlushFinalBlock()
' Convert our encrypted data from a memory stream into a byte array.
Dim cipherTextBytes As Byte() = memoryStream.ToArray()
' Close both streams.
memoryStream.Close()
cryptoStream.Close()
Encrypt = cipherTextBytes
End Function
Function Decrypt(ByVal input As Byte(), _
ByVal key As Byte(), _
ByVal iv As Byte()) _
As Byte()
Dim symmetricKey As New Security.Cryptography.AesManaged()
symmetricKey.Mode = Security.Cryptography.CipherMode.CBC
' Generate decryptor from the existing key bytes and initialization
' vector. Key size will be defined based on the number of the key
' bytes.
Dim decryptor As Security.Cryptography.ICryptoTransform
decryptor = symmetricKey.CreateDecryptor(key, iv)
' Define memory stream which will be used to hold encrypted data.
Dim memoryStream As New IO.MemoryStream(input)
' Define memory stream which will be used to hold encrypted data.
Dim cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
decryptor, _
Security.Cryptography.CryptoStreamMode.Read)
' Since at this point we don't know what the size of decrypted data
' will be, allocate the buffer long enough to hold ciphertext;
' plaintext is never longer than ciphertext.
Dim plainTextBytes As Byte()
ReDim plainTextBytes(input.Length)
' Start decrypting.
Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, _
0, _
plainTextBytes.Length)
' Close both streams.
memoryStream.Close()
cryptoStream.Close()
Decrypt = plainTextBytes
End Function
|