在同一进程中加密和解密时如何修复"Padding is invalid and cannot be removed"
How to fix "Padding is invalid and cannot be removed" when encrypting and decrypting in the same process
我正在尝试加密和解密 xml 文件。该程序尝试打开、编辑和重新加密数据,但出现错误 "System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed." 当我加密然后解密 运行 程序两次时,它工作正常,但程序产生错误两者都做的时候。
这是一个很常见的错误,但也是一个很模糊的错误,有很多不同之处"scenarios"。我已经搜索了一段时间来修复它,并且我已经在线尝试了所有 "fixes"。 None 已经工作了。
class Program
{
static void Main(string[] args)
{
}
public static void encFile(string input, string password)
{
GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
FileEncrypt(input, password);
ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
gch.Free();
}
public static string output;
public static void decFile(string input, string password)
{
GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
// Decrypt the file
output = FileDecrypt(input, password);
}
[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
/// <summary>
/// Encrypts a file from its path and a plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="password"></param>
private static void FileEncrypt(string inputFile, string password)
{
File.WriteAllText(Path.GetDirectoryName(inputFile) + "\" + Path.GetFileNameWithoutExtension(inputFile) + ".dat", Crypto.EncryptStringAES(File.ReadAllText(inputFile), "Password123!"));
}
/// <summary>
/// Decrypts an encrypted file with the FileEncrypt method through its path and the plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="outputFile"></param>
/// <param name="password"></param>
private static string FileDecrypt(string inputFile, string password)
{
return Crypto.DecryptStringAES(File.ReadAllText(inputFile), password);
}
}
public class Crypto
{
//While an app specific salt is not the best practice for
//password based encryption, it's probably safe enough as long as
//it is truly uncommon. Also too much work to alter this answer otherwise.
private static byte[] _salt = Encoding.ASCII.GetBytes("rxONBa*&e03!%76N9mBlbR#@Xl&A&w");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.Padding = PaddingMode.PKCS7;
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
aesAlg.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
运行下面先加密再解密的代码会报错:
static void Main(string[] args)
{
string password = "Password123!";
encFile(@"C:\DIR\test.xml", password);
decFile(@"C:\DIR\test.dat", password);
Console.WriteLine(output);
}
但是,如果您先尝试 运行 宁这个只加密文件的代码:
static void Main(string[] args)
{
string password = "Password123!";
encFile(@"C:\DIR\test.xml", password);
}
加密后在另一个进程中解密:
static void Main(string[] args)
{
string password = "Password123!";
decFile(@"C:\DIR\test.dat", password);
Console.WriteLine(output);
}
那么程序会正确输出内容,不会报错
如何在一个文件中加密和解密文件 运行,而不出现任何错误。
变量password
和同名参数指向同一个常量字符串。您的第一个方法将使该字符串归零。
static void Main(string[] args)
{
string password = "Password123!";
encFile(@"C:\KaliPatriot\test.xml", password);
// password is now "[=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=]"
decFile(@"C:\KaliPatriot\test.dat", password);
Console.WriteLine(output);
}
使用这样的字符串非常危险。字符串应该(并假设)是不可变的,.NET 也对字符串使用实习。
你已经在 C# 中获得了 UB(未定义行为),这并不值得骄傲。
我正在尝试加密和解密 xml 文件。该程序尝试打开、编辑和重新加密数据,但出现错误 "System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed." 当我加密然后解密 运行 程序两次时,它工作正常,但程序产生错误两者都做的时候。
这是一个很常见的错误,但也是一个很模糊的错误,有很多不同之处"scenarios"。我已经搜索了一段时间来修复它,并且我已经在线尝试了所有 "fixes"。 None 已经工作了。
class Program
{
static void Main(string[] args)
{
}
public static void encFile(string input, string password)
{
GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
FileEncrypt(input, password);
ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
gch.Free();
}
public static string output;
public static void decFile(string input, string password)
{
GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
// Decrypt the file
output = FileDecrypt(input, password);
}
[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
/// <summary>
/// Encrypts a file from its path and a plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="password"></param>
private static void FileEncrypt(string inputFile, string password)
{
File.WriteAllText(Path.GetDirectoryName(inputFile) + "\" + Path.GetFileNameWithoutExtension(inputFile) + ".dat", Crypto.EncryptStringAES(File.ReadAllText(inputFile), "Password123!"));
}
/// <summary>
/// Decrypts an encrypted file with the FileEncrypt method through its path and the plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="outputFile"></param>
/// <param name="password"></param>
private static string FileDecrypt(string inputFile, string password)
{
return Crypto.DecryptStringAES(File.ReadAllText(inputFile), password);
}
}
public class Crypto
{
//While an app specific salt is not the best practice for
//password based encryption, it's probably safe enough as long as
//it is truly uncommon. Also too much work to alter this answer otherwise.
private static byte[] _salt = Encoding.ASCII.GetBytes("rxONBa*&e03!%76N9mBlbR#@Xl&A&w");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.Padding = PaddingMode.PKCS7;
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
aesAlg.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
运行下面先加密再解密的代码会报错:
static void Main(string[] args)
{
string password = "Password123!";
encFile(@"C:\DIR\test.xml", password);
decFile(@"C:\DIR\test.dat", password);
Console.WriteLine(output);
}
但是,如果您先尝试 运行 宁这个只加密文件的代码:
static void Main(string[] args)
{
string password = "Password123!";
encFile(@"C:\DIR\test.xml", password);
}
加密后在另一个进程中解密:
static void Main(string[] args)
{
string password = "Password123!";
decFile(@"C:\DIR\test.dat", password);
Console.WriteLine(output);
}
那么程序会正确输出内容,不会报错
如何在一个文件中加密和解密文件 运行,而不出现任何错误。
变量password
和同名参数指向同一个常量字符串。您的第一个方法将使该字符串归零。
static void Main(string[] args)
{
string password = "Password123!";
encFile(@"C:\KaliPatriot\test.xml", password);
// password is now "[=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=]"
decFile(@"C:\KaliPatriot\test.dat", password);
Console.WriteLine(output);
}
使用这样的字符串非常危险。字符串应该(并假设)是不可变的,.NET 也对字符串使用实习。
你已经在 C# 中获得了 UB(未定义行为),这并不值得骄傲。