मैं कुछ सरल स्ट्रिंग एन्क्रिप्शन की जरूरत है, तो मैं निम्नलिखित कोड लिखा था (here से "प्रेरणा" के एक महान सौदा के साथ):खराब पासवर्ड क्यों होता है "पैडिंग अमान्य है और इसे हटाया नहीं जा सकता"?
// create and initialize a crypto algorithm
private static SymmetricAlgorithm getAlgorithm(string password) {
SymmetricAlgorithm algorithm = Rijndael.Create();
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
password, new byte[] {
0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
}
);
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
return algorithm;
}
/*
* encryptString
* provides simple encryption of a string, with a given password
*/
public static string encryptString(string clearText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/*
* decryptString
* provides simple decryption of a string, with a given password
*/
public static string decryptString(string cipherText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
कोड ठीक काम करने के लिए, सिवाय इसके कि जब एक गलत के साथ डेटा decrypting प्रकट होता है कुंजी, मुझे एक क्रिप्टोग्राफिक अपवाद मिलता है - "पैडिंग अमान्य है और इसे हटाया नहीं जा सकता" - cs.Close() लाइन पर decryptString में।
उदाहरण कोड:
string password1 = "password";
string password2 = "letmein";
string startClearText = "The quick brown fox jumps over the lazy dog";
string cipherText = encryptString(startClearText, password1);
string endClearText = decryptString(cipherText, password2); // exception thrown
मेरा प्रश्न है, इस उम्मीद की जा करने के लिए है? मैंने सोचा होगा कि गलत पासवर्ड के साथ डिक्रिप्ट करने से अपवाद के बजाय नॉनसेंस आउटपुट होगा।
इसने मुझे आपकी टिप्पणी के साथ इतना समय बचाया: '"कोड ठीक काम करता प्रतीत होता है, सिवाय इसके कि जब गलत कुंजी के साथ डेटा डिक्रिप्ट किया जाता है' 'i _swore_ मैंने चाबियाँ कॉपी की थीं, लेकिन 2x देखकर मैंने नहीं किया।उम्मीद है कि यह पैडिंग तंत्र या बदलते कोड को देखने से पहले किसी और की मदद करता है। – atconway