निम्नलिखित जितना आसान हो उतना सरल है, यह मानते हुए कि आप वास्तव में केवल एक स्ट्रिंग को एन्क्रिप्ट/डिक्रिप्ट करने और डिस्क पर संग्रहीत करने में सक्षम होना चाहते हैं। ध्यान दें कि यह पासवर्ड का उपयोग नहीं करता है, यह डेटा को सुरक्षित करने के लिए लॉग इन उपयोगकर्ता System.Security.Cryptography.DataProtectionScope.CurrentUser के सुरक्षा संदर्भ का उपयोग करता है।
public class SecureIt
{
static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("Salt Is Not A Password");
public static string EncryptString(System.Security.SecureString input)
{
byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
entropy,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
public static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
Convert.FromBase64String(encryptedData),
entropy,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
public static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
public static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
}
फिर एक स्ट्रिंग एन्क्रिप्ट करने के लिए:
var clearText = "Some string to encrypt";
var cypherText = SecureIt.EncryptString(SecureIt.ToSecureString(clearText));
और बाद में डिक्रिप्ट करने के लिए:
var clearText = SecureIt.ToInsecureString(SecureIt.DecryptString(cypherText));
स्रोत
2012-01-16 00:28:58
संबंधित प्रश्न: [? कैसे एक डेटाबेस या पाठ फ़ाइल में बाद में इसे बचाने के लिए एक पासवर्ड एन्क्रिप्ट करने] (http://stackoverflow.com/questions/ 541,219/कैसे करने वाली एन्क्रिप्ट एक पासवर्ड के लिए बचत यह बाद में-में-एक-डेटाबेस या पाठ फ़ाइल)। और बहुत कुछ, बहुत कुछ: ['सी # एन्क्रिप्ट पासवर्ड' युक्त प्रश्न] (http://stackoverflow.com/search?q=c%23+encrypt+password)। –
ध्यान दें कि जो कुछ भी आप करते हैं, आप ** * पासवर्ड * डिक्रिप्ट नहीं करते हैं **। इसके बजाय, आप सुनिश्चित करते हैं कि दो हैंश मैच। –
@ कोडीग्रे एसक्यूएल कनेक्शन स्ट्रिंग में हैश पासवर्ड भेजने का कोई तरीका है? – Odys