Encrypt String - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:AES

Description

Encrypt String

Demo Code

/*//from w  w  w  .j a  v a  2s.c  om
 * Copyright (c) 2007-2012, Masahiko Kamo (mkamo@mkamo.com).
 * All Rights Reserved.
 */
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{

        public static string EncryptString(string str, string password) {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();

            var data = System.Text.Encoding.UTF8.GetBytes(str);
        
            var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
            aes.Key = ResizeBytesArray(passwordBytes, aes.Key.Length);
            aes.IV = ResizeBytesArray(passwordBytes, aes.IV.Length);

            var stream = new System.IO.MemoryStream();
            var encryptor = aes.CreateEncryptor();
            var cryptStream = new System.Security.Cryptography.CryptoStream(
                stream,
                encryptor,
                System.Security.Cryptography.CryptoStreamMode.Write
            );
            try {
                cryptStream.Write(data, 0, data.Length);
                cryptStream.FlushFinalBlock();
                var encrypted = stream.ToArray();
                return System.Convert.ToBase64String(encrypted);

            } finally {
                cryptStream.Close();
                stream.Close();
            }
        }
}

Related Tutorials