Decrypt String with AesManaged - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:AES

Description

Decrypt String with AesManaged

Demo Code


using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.IO;//  w w  w . j  av a  2s. c o m
using System.Collections.Generic;
using System;

public class Main{
        public static string Decrypt(string input)
        {
            try
            {
                byte[] buffer = Convert.FromBase64String(input);
                byte[] salt = Encoding.UTF8.GetBytes("qwertyuiophoepqpqipi");
                AesManaged managed = new AesManaged();
                Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes("!@#$%^&*())_", salt);
                managed.BlockSize = managed.LegalBlockSizes[0].MaxSize;
                managed.KeySize = managed.LegalKeySizes[0].MaxSize;
                managed.Key = bytes.GetBytes(managed.KeySize / 8);
                managed.IV = bytes.GetBytes(managed.BlockSize / 8);
                ICryptoTransform transform = managed.CreateDecryptor();
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.Close();
                byte[] buffer3 = stream.ToArray();
                return Encoding.UTF8.GetString(buffer3, 0, buffer3.Length);
            }
            catch (Exception)
            {
                return "";
            }
        }
}

Related Tutorials