Save user and password without database use

Asked

Viewed 1,320 times

4

I am developing an application in C# of the kind Console, and I’m looking to save some sensitive settings like user, password and IP. The problem is, how to safely store this data locally without using a database anywhere.

For example, at first I thought about saving this data in an XML, but soon I saw that they would be totally exposed, so I thought of encrypting, but when I use them I need everything to be decrypted, including the password.

The question is, how to save this data in file securely in C#?

2 answers

3


  • It would be good for future references and especially for case the link breaks... Thanks I’ll take a look.

  • There in the article the method is already being applied Triple DES?

  • I find it difficult to break the link, especially because it is in Code Project, but soon edit the question and put.

  • 1

    Thanks, you answered perfectly.

2

You can do without using a commercial database, but you will end up creating your own "database" and all the mechanism to read, write and protect your file.

You can use an XML file and encrypt the data and serialize a class to XML and then when you need to use it you deserialize that file again to a class.

An even more secure way would be to use a file in XML format, use a file in binary format, (.dat, .bin, .what you want) and serialize+encrypt at the time of saving and deserialize/decrypt at the time of reading.

An easy idea would be to have a class that already does the encryption at the time of saving automatically and the reverse at the time of reading. Example:

public sealed class AccessData {
    private String _username;
    private String _password;
    private String _ipv4;

    [XmlIgnore] //Esta propriedade não irá para o arquivo .XML quando for serializada
    public String UserName {
         get { return _username; }
         set { _username = value; }
    }

    [XmlElement("UserName")] //No XML o valor será armazenado em uma tag "UserName"
    public String UserNameSecure { 
        get { return Security.Encrypt("S3Nh@S3GuR@", _username); }
        set { _username = Security.Decrypt("S3Nh@S3GuR@", value); }
    }

    [XmlIgnore] //Esta propriedade não irá para o arquivo .XML quando for serializada
    public String Password {
         get { return _password; }
         set { _password = value; }
    }

    [XmlElement("Password")] //No XML o valor será armazenado em uma tag "Password"
    public String PasswordSecure { 
        get { return Security.Encrypt("S3Nh@S3GuR@", _password); }
        set { _password = Security.Decrypt("S3Nh@S3GuR@", value); }
    }

      [XmlIgnore] //Esta propriedade não irá para o arquivo .XML quando for serializada
    public String IPV4 {
         get { return _ipv4; }
         set { _ipv4 = value; }
    }

    [XmlElement("IPAddress")] //No XML o valor será armazenado em uma tag "IPAddress"
    public String IPV4Secure { 
        get { return Security.Encrypt("S3Nh@S3GuR@", _ipv4); }
        set { _ipv4 = Security.Decrypt("S3Nh@S3GuR@", value); }
    }
}

internal static class Security {
    private const String SaltKey = "umaStringDeSalt";
    private const String ViKey = "UmaChaveQualquer";

    public static String Encrypt(String password, String value){
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(value);

        byte[] keyBytes = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
        var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(ViKey));

        byte[] cipherTextBytes;

        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                cipherTextBytes = memoryStream.ToArray();
                cryptoStream.Close();
            }
            memoryStream.Close();
        }
        return Convert.ToBase64String(cipherTextBytes);
    }

    public static String Decrypt(String password, String value)
    {
        byte[] cipherTextBytes = Convert.FromBase64String(value);
        byte[] keyBytes = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.None };

        var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(ViKey));
        var memoryStream = new MemoryStream(cipherTextBytes);
        var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        var plainTextBytes = new byte[cipherTextBytes.Length];

        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
    }
}

Note that the class properties are Username, Password and IPV4 These are the properties you will use in your code. Usernamesecure, Passwordsecure and Ipv4secure properties are for XML serialization only, note that they encrypt and decrypt the data.

An example of use:

var objeto = new AccessData();
objeto.Username = "Guilherme";
objeto.Password = "123456";
objeto.IPV4 = "192.168.1.1";   
var serializer = new SerializationHelper(); //classe que você irá criar para serializar arquivos XML.
serializer.Save("dadosDeAcesso.xml",objeto); //um método "Save" deverá salvar um objeto qualquer (objeto) em um arquivo qualquer (dadosDeAcesso.xml)

How to serialize a class for XML and an XML file

Serialize a class to an XML file

Serialize a class to XML

  • So I did something similar, I’m not wearing one arquivo.xml, I did something similar to what you said, but not so optimized, I’m new to C#, I didn’t know I could serialize a class for XML... : D vlw

  • Yes, you can serialize any "publish" class and its public properties to XML, JSON or binary. Other formats you need to create your own "seriliazer/deserializer"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.