Mon encryptage et les méthodes de décryptage:tableau de déchiffrage d'octets avec SymmetricAlgorithm et CryptoStream
private static SymmetricAlgorithm GetAlgorithm(string password)
{
using (Rijndael algorithm = Rijndael.Create())
{
using (Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(password, new byte[]
{
0x53, 0x6f, 0x64, 0x69, 0x75, 0x6d, 0x20, 0x43, 0x68, 0x6c, 0x6f, 0x72, 0x69, 0x64, 0x65
}))
{
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
}
return algorithm;
}
}
public static byte[] EncryptBytes(byte[] clearBytes, string password)
{
ICryptoTransform encryptor;
using (SymmetricAlgorithm algorithm = GetAlgorithm(password))
encryptor = algorithm.CreateEncryptor();
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
public static byte[] DecryptBytes(byte[] cipherBytes, string password)
{
ICryptoTransform decryptor;
using (SymmetricAlgorithm algorithm = GetAlgorithm(password))
decryptor = algorithm.CreateDecryptor();
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length); //here is the exception thrown
cs.FlushFinalBlock();
return ms.ToArray();
}
}
Comment j'appeler les méthodes:
byte[] prev = File.ReadAllBytes(path + sourcefile);
byte[] enc = Encryption.EncryptBytes(prev, password);
byte[] dec = Encryption.DecryptBytes(enc, password);
File.WriteAllBytes(path + targetfile, dec);
Lorsque je tente de déchiffrer le tableau d'octets que je reçois l'exception suivante:
System.Security.Cryptography.CryptographicException
Additional information: padding is invalid and cannot be removed
J'ai déjà lu quelques solutions possibles mais aucune d'elles n'a résolu mon problème. La clé et IV (InitialisationVector) sont les mêmes, lorsque je crypte et décrypte, ce n'est certainement pas la raison.
Le 'GetAlgorithm' est MAUVAIS: vous retournez un' 'Disposed' algorithm' – xanatos
mais quand dois-je besoin de disposer alors? –
Vous êtes 'Disposing' l'algorithme dans la méthode d'appel de' GetAlgorithm() ' – xanatos