Occasionnel de Mauvaises Données d'Erreur, tandis que le décryptage de la chaîne : Système.De sécurité.La cryptographie.CryptographicException

Dans mon ASP.NET Application web forms (L'application est en cours d'exécution sur windows server 2008 R2, IIS 7.5 et d'Exécution v4.0 en Mode Intégré d'Application de la Piscine si c'est important), je suis le cryptage des données, de les mettre dans la chaîne de Requête et le décryptage de données à l'aide de System.Security.Cryptography.SymmetricAlgorithm classe. Mais je suis parfois d'avoir quelques problèmes avec décrypter les données, je suis l'exception suivante;

De Mauvaises Données.

Description: Une exception non gérée
s'est produite pendant l'exécution de la
demande web actuelle. Veuillez passer en revue les
trace de la pile pour plus d'informations sur
l'erreur et où il trouve son origine dans
le code.

Détails De L'Exception:
Système.De sécurité.La cryptographie.CryptographicException:
De Mauvaises Données.

Source De L'Erreur:

Une exception non gérée s'est généré
au cours de l'exécution de la
demande web. Les informations concernant les
origine et l'emplacement de l'exception
peut être identifié à l'aide de l'exception
trace de la pile ci-dessous.

Trace De La Pile:

[CryptographicException: Les Données De Mauvaise Qualité. ]

Système.De sécurité.La cryptographie.CryptographicException.ThrowCryptographicException(Int32
rh) +33

Système.De sécurité.La cryptographie.Utils._DecryptData(SafeKeyHandle
hKey, Byte[] data, Int32 de l'ib, Int32 cb,
Byte[]& outputBuffer, Int32
outputOffset, PaddingMode PaddingMode,
Boolean fDone) +0

Système.De sécurité.La cryptographie.CryptoAPITransform.TransformFinalBlock(Byte[]
inputBuffer, Int32 inputOffset, Int32
inputCount) +313

Système.De sécurité.La cryptographie.CryptoStream.FlushFinalBlock()
+33 Cryptography35.SymmetricEncryptionUtility.DecryptData(Byte[]
des données, Chaîne keyFile)
E:\Documents\@Library\Cryptography35\Cryptography35\SymmetricEncryptionUtility.cs:124
Cryptography35.SymmetricQueryString.SymmetriclyEncryptedQueryString..ctor(String
encryptedData, Chaîne keyfilename,
Chaîne algorithmname)
E:\Documents\@Library\Cryptography35\Cryptography35\SymmetricQueryString\SymmetriclyEncryptedQueryString.cs:67
WebForms.Web.Les vues.purchase_a.GetSymmetriclyEncryptedQueryString()
dans
E:\Documents\WebForms.Web\Views\achat-un.aspx.cs:35
WebForms.Web.Les vues.purchase_a.Page_Load(Object
sender, EventArgs e) dans
E:\Documents\WebForms.Web\Views\achat-un.aspx.cs:56
Système.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
fp, l'Objet o, t Objet, EventArgs e)
+14 Système.Web.Util.CalliEventHandlerDelegateProxy.Rappel(Objet
sender, EventArgs e) +35

Système.Web.L'INTERFACE utilisateur.De contrôle.OnLoad(EventArgs
e) +91

Système.Web.L'INTERFACE utilisateur.De contrôle.LoadRecursive()
+74 Système.Web.L'INTERFACE utilisateur.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +2207
Les Informations De Version: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.1

Comme je l'ai indiqué, j'obtiens cette erreur à l'occasion, et pas à chaque fois que je lance. Je ne sais pas où je suis de faire le mal (sur l'étape de chiffrement ou de déchiffrement de la scène) Voici le code que j'ai utilisé pour cela;

private SymmetriclyEncryptedQueryString GetSymmetriclyEncryptedQueryString() {

    #region _decrypting the value

    string KeyFileName;
    string AlgorithmName = "DES";

    Cryptography35.SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
    KeyFileName = HttpContext.Current.Server.MapPath("~/@config/") + "\\symmetric_key.config";

    #endregion

    #region _reading and assigning the value

    if (Request.QueryString["q"] == null)
        throw new NullReferenceException("QueryString value is null on search result page");

    SymmetriclyEncryptedQueryString QueryString = new SymmetriclyEncryptedQueryString(Request.QueryString["q"], KeyFileName, AlgorithmName);

    #endregion

    return QueryString;
}

SymmetriclyEncryptedQueryString Classe

public class SymmetriclyEncryptedQueryString : System.Collections.Specialized.StringDictionary {
public string KeyFileName { get; set; }
public string AlgorithmName { get; set; }
///<summary>
///Use this for encrypte the value
///</summary>
///<param name="keyfilename"></param>
///<param name="algorithmname"></param>
public SymmetriclyEncryptedQueryString(string keyfilename, string algorithmname) {
KeyFileName = keyfilename;
AlgorithmName = algorithmname;
}
///<summary>
///Use this for decrypte the value.
///</summary>
///<param name="encryptedData"></param>
///<param name="keyfilename"></param>
///<param name="algorithmname"></param>
public SymmetriclyEncryptedQueryString(string encryptedData, string keyfilename, string algorithmname) {
#region _initials
KeyFileName = keyfilename;
AlgorithmName = algorithmname;
if (String.IsNullOrEmpty(AlgorithmName)){
SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
}
else{
SymmetricEncryptionUtility.AlgorithmName = "DES";
}
SymmetricEncryptionUtility.ProtectKey = false;
//Check for encryption key
if (!File.Exists(KeyFileName)){
throw new FileNotFoundException("Keyfilename for  SymmetriclyEncryptedQueryString is not found on '" + KeyFileName + "'!");
}
#endregion
//Arrange the data
//In order not to get following exception
//Invalid length for a Base-64 char array.
//byte[] RawData = Convert.FromBase64String(encryptedData);
encryptedData = encryptedData.Replace(" ", "+");
int mod4 = encryptedData.Length % 4;
if (mod4 > 0)
encryptedData += new string('=', 4 - mod4);
//Decrypt data passed in
byte[] RawData = Convert.FromBase64String(encryptedData);
string DecryptedVal = SymmetricEncryptionUtility.DecryptData(RawData, KeyFileName);
string StringData = DecryptedVal;
//Split the data and add the contents
int Index;
string[] SplittedData = StringData.Split(new char[] { '&' });
foreach (string SingleData in SplittedData) {
Index = SingleData.IndexOf('=');
base.Add(
HttpUtility.UrlDecode(SingleData.Substring(0, Index)),
HttpUtility.UrlDecode(SingleData.Substring(Index + 1))
);
}
}
public override string ToString() {
#region _initials
if (String.IsNullOrEmpty(AlgorithmName)) {
SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
} else {
SymmetricEncryptionUtility.AlgorithmName = "DES";
}
SymmetricEncryptionUtility.ProtectKey = false;
//Check for encryption key
if (!File.Exists(KeyFileName)) {
throw new FileNotFoundException("Keyfilename for AsymmetriclyEncryptedQueryString is not found on '" + KeyFileName + "'!");
}
#endregion
#region _prepare for querystring
//Go through the contents and build a 
//typical query string
StringBuilder Content = new StringBuilder();
foreach (string key in base.Keys) {
Content.Append(HttpUtility.UrlEncode(key));
Content.Append("=");
Content.Append(HttpUtility.UrlEncode(base[key]));
Content.Append("&");
}
//Remove the last '&'
Content.Remove(Content.Length - 1, 1);
#endregion
#region _encrypt the contents
//Now encrypt the contents
byte[] data = SymmetricEncryptionUtility.EncryptData(Content.ToString(), KeyFileName);
string EncryptedVal = Convert.ToBase64String(data);
#endregion
return EncryptedVal;
}
}

SymmetricEncryptionUtility Classe

public static class SymmetricEncryptionUtility {
private static bool _ProtectKey;
private static string _AlgorithmName;
//Shhh!!! Don't tell anybody!
private const string MyKey = "m$%&kljasldk$%/65asjdl";
public static string AlgorithmName {
get { return _AlgorithmName; }
set { _AlgorithmName = value; }
}
public static bool ProtectKey {
get { return _ProtectKey; }
set { _ProtectKey = value; }
}
public static void GenerateKey(string targetFile) {
//Create the algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.GenerateKey();
//No get the key
byte[] Key = Algorithm.Key;
if (ProtectKey)
{
//Use DPAPI to encrypt key
Key = ProtectedData.Protect(
Key, null, DataProtectionScope.LocalMachine);
}
//Store the key in a file called key.config
using (FileStream fs = new FileStream(targetFile, FileMode.Create))
{
fs.Write(Key, 0, Key.Length);
}
}
public static void ReadKey(SymmetricAlgorithm algorithm, string keyFile)
{
byte[] Key;
using (FileStream fs = new FileStream(keyFile, FileMode.Open))
{
Key = new byte[fs.Length];
fs.Read(Key, 0, (int)fs.Length);
}
if (ProtectKey)
algorithm.Key = ProtectedData.Unprotect(Key, null, DataProtectionScope.LocalMachine);
else
algorithm.Key = Key;
}
public static byte[] EncryptData(string data, string keyFile)
{
//Convert string data to byte array
byte[] ClearData = Encoding.UTF8.GetBytes(data);
//Now Create the algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
ReadKey(Algorithm, keyFile);
//Encrypt information
MemoryStream Target = new MemoryStream();
//Append IV
Algorithm.GenerateIV();
Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);
//Encrypt actual data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(ClearData, 0, ClearData.Length);
cs.FlushFinalBlock();
//Output the bytes of the encrypted array to the textbox
return Target.ToArray();
}
public static string DecryptData(byte[] data, string keyFile) {
//Now create the algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
ReadKey(Algorithm, keyFile);
//Decrypt information
MemoryStream Target = new MemoryStream();
//Read IV
int ReadPos = 0;
byte[] IV = new byte[Algorithm.IV.Length];
Array.Copy(data, IV, IV.Length);
Algorithm.IV = IV;
ReadPos += Algorithm.IV.Length;
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(data, ReadPos, data.Length - ReadPos);
cs.FlushFinalBlock();
//Get the bytes from the memory stream and convert them to text
return Encoding.UTF8.GetString(Target.ToArray());
}
}

Mise à JOUR
J'ai pensé que quelque chose d'autre. Sur une de mes pages, je suis en train de faire la chose suivante;

protected override void OnInit(EventArgs e) {
string url = Request.Url.AbsoluteUri.ToLower();
if (url.StartsWith("http:"))
{
Response.Redirect(url.Replace("http://", "https://"), true);
}
}

J'ai pensé qu'il provoque le problème. (N'oubliez pas que mes données chiffrées se trouve à l'intérieur de la Chaîne de Requête) lorsque j'essaie d'atteindre la page de http et il redirige vers le https et de la flèche. il me donne cette erreur. ok maintenant j'ai trouvé la source de l'erreur, mais il ne devrait pas se produire de toute façon.

OriginalL'auteur tugberk | 2011-07-02