0% found this document useful (0 votes)
11 views

Sample Code

Uploaded by

jgd.lok
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Sample Code

Uploaded by

jgd.lok
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;

public class AESEncrytDecry


{
public static string key_Val = "k2hLr4X0ozNyZByj5DT66edtCEee1x+6";

public static string DecryptAES(string encryptedValue)


{
if (string.IsNullOrEmpty(encryptedValue))
{
return encryptedValue;
}

if (encryptedValue.Substring(0, 2) == "\\x")
{
encryptedValue = encryptedValue.Remove(0, 2);
}

byte[] key = Encoding.UTF8.GetBytes(key_Val);


using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = key;
aesAlg.Mode = CipherMode.ECB;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key,
aesAlg.IV);
MemoryStream msDecrypt = new
MemoryStream(HexToByteArray(encryptedValue));
CryptoStream csDecrypt = new
System.Security.Cryptography.CryptoStream(msDecrypt, decryptor,
CryptoStreamMode.Read);

StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt);

return srDecrypt.ReadToEnd();

}
}

public static string Encrypt(string plainText)


{
if (string.IsNullOrEmpty(plainText))
{
return plainText;
}

byte[] Key = Encoding.UTF8.GetBytes(key_Val);


using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.Mode = CipherMode.ECB;

ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key,


aesAlg.IV);
using (MemoryStream outputStream = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(outputStream,
encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
return "\\x" + ByteArrayToString(outputStream.ToArray());

}
}
}

public static string ByteArrayToString(byte[] ba)


{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}

private static byte[] HexToByteArray(string hex)


{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
int iPos = 0;
for (int i = 0; i <= NumberChars - 1; i += 2)
{
bytes[iPos] = Convert.ToByte(hex.Substring(i, 2), 16);
iPos += 1;
}
return bytes;
}

You might also like