All pastes #745897 Raw Edit

DESLib

public text v1 · immutable
·published 2007-10-22 19:58 UTC
rendered paste body
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace EncryptionClass
{
    internal class DESLibrary
    {
        private static byte[] InitializationVector = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };

        public static string FromBase64String(string CipherText, string sKey)
        {
            byte[] CipherTextBytes = new byte[CipherText.Length - 1];
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

            byte[] PrivateKey = System.Text.Encoding.UTF8.GetBytes(sKey);
            CipherTextBytes = Convert.FromBase64String(CipherText);

            using (MemoryStream InMemoryStream = new MemoryStream())
            {
                using (CryptoStream CipherStream =
                        new CryptoStream(InMemoryStream, DES.CreateDecryptor(PrivateKey, InitializationVector), CryptoStreamMode.Write)) 
                {
                    CipherStream.Write(CipherTextBytes, 0, CipherTextBytes.Length);
                    CipherStream.FlushFinalBlock();

                    return System.Text.Encoding.UTF8.GetString(InMemoryStream.ToArray());
                }
            }
        }

        public static string ToBase64String(string PlainText, string sKey)
        {
            byte[] PrivateKey = System.Text.Encoding.UTF8.GetBytes(sKey);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            
            byte [] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
            
            using (MemoryStream InMemoryStream = new MemoryStream())
            {
                using (CryptoStream CipherStream = 
                       new CryptoStream(InMemoryStream,DES.CreateEncryptor(PrivateKey,InitializationVector),CryptoStreamMode.Write))
                {
                    CipherStream.Write(PlainTextBytes,0,PlainTextBytes.Length);
                    CipherStream.FlushFinalBlock();

                    return Convert.ToBase64String(InMemoryStream.ToArray());
                }

            }

        }

    }


    public class EncryptionEngine
    {
        public string Encrypt(string PlainText, string sKey)
        {
            return EncryptionClass.DESLibrary.ToBase64String(PlainText, sKey);
        }

        public string Decrypt(string CipherText, string sKey)
        {
            return EncryptionClass.DESLibrary.FromBase64String(CipherText, sKey);
        }

    }
}