вторник, 11 сентября 2018 г.

Crypt. C#
Появилась задача сделать ActiveX компонент для encrypt/decrypt со статическими ключами/солью. Разбор полётов с примерами породил такой сырец:
(внимание гостям, это рабочий варинт. не прилизан, не урезан не обфусцирован, много копи-паст :))
Как есть. Вектор и соль менять.

using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace AlexCrypt
{
    [ComVisible(true)]
    [Guid("235D87E1-9BFA-47AB-9E97-CF1A2D342054")]
    public interface IAlexCrypt
    {
        string Encrypt(
            string cipherText,
            string passPhrase);
        string Decrypt(
            string cipherText,
            string passPhrase);
    }

    [Guid("162E64E6-99D6-47BB-B52E-1A4205EFF5AF")]
    [ClassInterface(ClassInterfaceType.None)]
    //[ProgId("AlexCrypt")]
    [ComVisible(true)]
    public class AlexCrypt : IAlexCrypt
    {
        public string Encrypt
        (
            string plainText,
            string passPhrase)
        {
            string saltValue = "*4b5FHMwa$h22=Wh";
            string hashAlgorithm = "SHA1";
            int passwordIterations = 2;
            string initVector = "sQY*K&TF8MMcR3=r";
            int keySize = 256;
            string cipherText = "";

            try
            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                PasswordDeriveBytes password = new PasswordDeriveBytes
                (
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations
                );
                byte[] keyBytes = password.GetBytes(keySize / 8);
                RijndaelManaged symmetricKey = new RijndaelManaged();
                symmetricKey.Mode = CipherMode.CBC;
                ICryptoTransform encryptor = symmetricKey.CreateEncryptor
                (
                    keyBytes,
                    initVectorBytes
                );
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    encryptor,
                    CryptoStreamMode.Write
                );

                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                byte[] cipherTextBytes = memoryStream.ToArray();
                memoryStream.Close();
                cryptoStream.Close();
                cipherText = Convert.ToBase64String(cipherTextBytes);
            }
            catch
            {
                cipherText = "Error";
            }
            return cipherText;
        }

        public string Decrypt
        (
            string cipherText,
            string passPhrase
        )
        {
            string saltValue = "*4b5FHMwa$h22=Wh";
            string hashAlgorithm = "SHA1";
            int passwordIterations = 2;
            string initVector = "sQY*K&TF8MMcR3=r";
            int keySize = 256;
            string plainText = "";
            try
            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
                PasswordDeriveBytes password = new PasswordDeriveBytes
                (
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations
                );
                byte[] keyBytes = password.GetBytes(keySize / 8);
                RijndaelManaged symmetricKey = new RijndaelManaged();
                symmetricKey.Mode = CipherMode.CBC;
                ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                (
                    keyBytes,
                    initVectorBytes
                );
                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
                CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    decryptor,
                    CryptoStreamMode.Read
                );
                byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                int decryptedByteCount = cryptoStream.Read
                (
                    plainTextBytes,
                    0,
                    plainTextBytes.Length
                );
                memoryStream.Close();
                cryptoStream.Close();
                plainText = Encoding.UTF8.GetString
                (
                    plainTextBytes,
                    0,
                    decryptedByteCount
                );
            }
            catch
            {   
                plainText = "Error";
            }
            return plainText;
        }
    }
}

Комментариев нет:

Отправить комментарий