using System;
using System.Security.Cryptography;
using System.IO;
namespace Encrypt_Decrypt
{
class Program
{
static void Main(string[] args)
{
Program program=new Program();
String encString = program.Encrypt("Your Password !", "3r%bh#ed");
Console.WriteLine(encString);
Console.WriteLine(program.Decrypt(encString, "3r%bh#ed"));
Console.Read();
}
public string Encrypt(string strText, string strEncrypt)
{
// Convert strings into byte arrays.
byte[] byKey = new byte[20];
byte[] dv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
// Create DESCryptoServiceProvider object
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
// Convert our plaintext into a byte array.
byte[] inputArray = System.Text.Encoding.UTF8.GetBytes(strText);
// Define memory stream which will be used to hold encrypted data
MemoryStream ms = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, dv),
CryptoStreamMode.Write);
// Start encrypting.
cs.Write(inputArray, 0, inputArray.Length);
// Finish encrypting.
cs.FlushFinalBlock();
// Convert encrypted data into a base64-encoded string and
// Return encrypted string.
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
public string Decrypt(string strText, string strEncrypt)
{
// Convert strings into byte arrays.
byte[] bKey = new byte[20];
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
bKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
// Create DESCryptoServiceProvider object
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
// Convert our plaintext into a byte array.
Byte[] inputByteArray = inputByteArray = Convert.FromBase64String(strText);
// Define memory stream which will be used to hold encrypted data
MemoryStream ms = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bKey, IV), CryptoStreamMode.Write);
// Start decrypting.
cs.Write(inputByteArray, 0, inputByteArray.Length);
// Finish decrypting.
cs.FlushFinalBlock();
// Convert decrypted data into a string.
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
// Return decrypted string.
return encoding.GetString(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
}
}
No comments:
Post a Comment