Encrypt and Decrypt Data Using the Data Protection API - CSharp Security

CSharp examples for Security:Cryptography

Description

Encrypt and Decrypt Data Using the Data Protection API

Demo Code


using System;/*ww w.ja  v a2  s .  com*/
using System.Text;
using System.Security.Cryptography;

class MainClass
    {
        public static void Main()
        {
            Console.Write("Enter the string to encrypt: ");
            string str = Console.ReadLine();

            byte[] entropy = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };

            byte[] enc = ProtectedData.Protect(Encoding.Unicode.GetBytes(str),
                entropy, DataProtectionScope.LocalMachine);

            Console.WriteLine("\nEncrypted string = {0}", BitConverter.ToString(enc));

            byte[] dec = ProtectedData.Unprotect(enc, entropy, DataProtectionScope.CurrentUser);

            Console.WriteLine("\nDecrypted data using CurrentUser scope = {0}", Encoding.Unicode.GetString(dec));

        }
    }

Result


Related Tutorials