Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

winforms - Working with Registry in C# 2.0 (Windows Forms)

I'm a newbie to Windows Forms.

I'm designing an Windows Application in .Net Framework 2.0 in which, I need to Store a UserName and Password somewhere in the System and access them every time I open My Application and Some times I need to change those credentials on User command.

I heard registry is the Best way in doing so. I know Nothing About Using Registry in C# .Net.

So Can you Help me in

How To Get Values which are In Registry, and how to Set a Value to Registry. ??

I'm Using .Net Framework 2.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The subject is very broad. You should start reading on MSDN about the class

Microsoft.Win32.RegistryKey

But I really suggest to avoid the registry altogether.
Allowing the registry to store configuration info for normal applications has been a mistake from the start by Microsoft.

You could write a simple hashing function, apply it to your username and password and store the result in a file located in the ApplicationData folder. At the next run check if the file exist, read it and compare its content with the hashing of username and password.

Here a rough example, just to let you start on your own code.

private void button1_Click(object sender, EventArgs e)
{
    string user = "Steve";
    string pass = "MyPass";

    string hashedUser = GetHashedText(user);
    string hashedPass = GetHashedText(pass);

    string file = Path.Combine(Environment.GetFolderPath 
                       (Environment.SpecialFolder.ApplicationData), 
                       "MyKeys.txt");

    if (File.Exists(file))
    {
        using (StreamReader sr = new StreamReader(file))
        {
            string recordedUser = sr.ReadLine();
            string recordedPass = sr.ReadLine();
            if (recordedUser == user && recordedPass == pass)
                MessageBox.Show("User validated");
            else
                MessageBox.Show("Invalid user");
        }
    }
    else
    {
        using (StreamWriter sw = new StreamWriter(file, false))
        {
            sw.WriteLine(hashedUser);
            sw.WriteLine(hashedPass);
        }

    }
}

private string GetHashedText(string inputData)
{ 
    byte[] tmpSource;
    byte[] tmpData;
    tmpSource = ASCIIEncoding.ASCII.GetBytes(inputData);
    tmpData = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
    return Convert.ToBase64String(tmpData);
}

EDIT: Based on your comment, it seems that you need a crypt and decrypt function. The code below is taken and adapted from the Extension Overflow, where you can find other useful methods. Now, before write to disk, call the Encrypt method with the string to encrypt and a key. After reading, call the Decrypt method passing the crypted text and the secret key.

string cryptedUser = Encrypt(user, "your_secret_key_ABCDEFG");
....

public string Encrypt(string stringToEncrypt, string key)
{
    if (string.IsNullOrEmpty(stringToEncrypt))
        throw new ArgumentException("An empty string value cannot be encrypted.");
    if (string.IsNullOrEmpty(key))
        throw new ArgumentException("Cannot encrypt using an empty key.");

    CspParameters cspp = new CspParameters();
    cspp.KeyContainerName = key;
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
    rsa.PersistKeyInCsp = true;
    byte[] bytes = rsa.Encrypt(UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);
    return BitConverter.ToString(bytes);
}

string clearText = Decrypt(cryptedText, "your_secret_key_ABCDEFG");
....

public string Decrypt(string stringToDecrypt, string key)
{
    string result = null;
    if (string.IsNullOrEmpty(stringToDecrypt))
        throw new ArgumentException("An empty string value cannot be encrypted.");
    if (string.IsNullOrEmpty(key))
        throw new ArgumentException("Cannot decrypt using an empty key");
    try
    {
        CspParameters cspp = new CspParameters();
        cspp.KeyContainerName = key;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
        rsa.PersistKeyInCsp = true;
        string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, 
                                 StringSplitOptions.None);
        byte[] decryptByteArray = Array.ConvertAll<string, byte>
                                 (decryptArray, (s => Convert.ToByte(byte.Parse(s,
                                 System.Globalization.NumberStyles.HexNumber))));
        byte[] bytes = rsa.Decrypt(decryptByteArray, true);
        result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
    }
    finally
    {
        // no need for further processing
    }
    return result;
}

Of course, I assume that the security level required by your application allows that username ans passwords will be stored in the local system. (And as you know, everything that is stored on the local system is not very secure)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...