using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace API.HelloWorld.Secure
{
public class AesSecure
{
private static readonly string KEY = "Hello";
/// <summary>
/// output Base64 Encoding
/// 암호화
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string EncryptString(string plainText)
{
try
{
if (plainText == null) return null;
if (plainText.Trim().Equals("")) return null;
byte[] plainTextBytes = System.Text.Encoding.Unicode.GetBytes(plainText);
byte[] salt = Encoding.ASCII.GetBytes(KEY.Length.ToString());
RijndaelManaged RijndaelCipher = new RijndaelManaged();
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(KEY, salt);
ICryptoTransform encryptor = RijndaelCipher.CreateEncryptor(secretKey.GetBytes(32),
secretKey.GetBytes(16));
using (MemoryStream ms = new MemoryStream())
{
CryptoStream cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = ms.ToArray();
ms.Close();
cryptoStream.Close();
string encryptedData = Convert.ToBase64String(cipherBytes);
return encryptedData;
}
}
catch
{
return null;
}
}
/// <summary>
/// Output Unicode encording
/// 복호화
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string DecryptString(string plainText)
{
try
{
if (plainText == null) return null;
if (plainText.Trim().Equals("")) return null;
byte[] plainTextBytes = Convert.FromBase64String(plainText);
byte[] salt = Encoding.ASCII.GetBytes(KEY.Length.ToString());
RijndaelManaged RijndaelCipher = new RijndaelManaged();
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(KEY, salt);
ICryptoTransform decryptor = RijndaelCipher.CreateDecryptor(secretKey.GetBytes(32),
secretKey.GetBytes(16));
using (MemoryStream ms = new MemoryStream(plainTextBytes))
{
CryptoStream cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
int decryptedCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
ms.Close();
cryptoStream.Close();
string decryptedData = Encoding.Unicode.GetString(plainTextBytes, 0, decryptedCount);
return decryptedData;
}
}
catch
{
return null;
}
}
}
}
'개발관련 > C#' 카테고리의 다른 글
class || struct <=> byte Array 변환 (0) | 2017.09.24 |
---|---|
ObjectSerialize (0) | 2017.08.10 |
모든 타입 xmlWriter (0) | 2017.08.10 |
XmlSerializer (0) | 2017.08.03 |
Http Handler 비동기 처리 (0) | 2017.07.25 |