vb net code snippets for storing password 1

vb net code snippets for storing password

    /// 
    /// Encrypts a given password and returns the encrypted data
    /// as a base64 string.
    /// 
    /// An unencrypted string that needs
    /// to be secured.
    /// A base64 encoded string that represents the encrypted
    /// binary data.
    /// 
    /// This solution is not really secure as we are
    /// keeping strings in memory. If runtime protection is essential,
    ///  should be used.
    /// If 
    /// is a null reference.
    public string Encrypt(string plainText)
    {
        if (plainText == null) throw new ArgumentNullException("plainText");

        //encrypt data
        var data = Encoding.Unicode.GetBytes(plainText);
        byte[] encrypted = ProtectedData.Protect(data, null, Scope);

        //return as base64 string
        return Convert.ToBase64String(encrypted);
    }

    /// 
    /// Decrypts a given string.
    /// 
    /// A base64 encoded string that was created
    /// through the  or
    ///  extension methods.
    /// The decrypted string.
    /// Keep in mind that the decrypted string remains in memory
    /// and makes your application vulnerable per se. If runtime protection
    /// is essential,  should be used.
    /// If 
    /// is a null reference.
    public string Decrypt(string cipher)
    {
        if (cipher == null) throw new ArgumentNullException("cipher");

        //parse base64 string
        byte[] data = Convert.FromBase64String(cipher);

        //decrypt data
        byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);
        return Encoding.Unicode.GetString(decrypted);
    }

Here is what the above code is Doing:
1. It’s creating a class called “ProtectedData”
2. It’s creating a method called “Encrypt” that takes a string as a parameter
3. It’s creating a method called “Decrypt” that takes a string as a parameter
4. It’s creating a method called “Encrypt” that takes a SecureString as a parameter
5. It’s creating a method called “Decrypt” that takes a SecureString as a parameter

Similar Posts