반응형
Notice
Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Do Something IT

유니티 에디터 문자 암호화 복호화 본문

Unity3D

유니티 에디터 문자 암호화 복호화

아낙시만더 2017. 11. 1. 14:34
반응형
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System;

public class csCDNPIDEncipherment : EditorWindow {
    public delegate string EnDel(string InputText, string Password);
    string _strTarget = "";
    string _strEncoTarget = "";
    static float _width = 1000;
    static float _height = 800;
    float _fontWidth = 15;
    string _password = "w12313s";
    //bool groupEnabled;
    //bool myBool = true;
    //float myFloat = 1.23f;

    // Add menu named "My Window" to the Window menu
    [MenuItem("SnowDog/CDNPIDEncipherment")]
    static void Init()
    {
        // Get existing open window or if none, make a new one:
        csCDNPIDEncipherment window = (csCDNPIDEncipherment)EditorWindow.GetWindow(typeof(csCDNPIDEncipherment));
        window.maxSize = new Vector2(_width, _height);
        window.minSize = window.maxSize;
        window.Show();
    }

    void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Input PID or encoded PID", EditorStyles.boldLabel);
        GUILayout.Label("Result", EditorStyles.boldLabel);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        _strTarget = EditorGUILayout.TextField(_strTarget, GUILayout.Width(500), GUILayout.Height(700));
        EditorGUILayout.TextField(_strEncoTarget, GUILayout.Height(700));
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Encrypt(암호화)", GUILayout.Height(50)))
        {
            GetResultValue(EncryptString);
        }
        if (GUILayout.Button("Decrypt(복호화)", GUILayout.Height(50)))
        {
            GetResultValue(DecryptString);
        }
        if (GUILayout.Button("clear", GUILayout.Height(50)))
        {
            _strTarget = "";
            _strEncoTarget = "";
        }
        EditorGUILayout.EndHorizontal();
    }

/// 
    /// 1.변환될 스트링 변화 
    /// 2.배열 처리
    /// 3.암호화 복호화
    /// 
    /// 
    void GetResultValue(EnDel EnFunc)
    {
        _strEncoTarget = "";
        //공백제거
        _strTarget = Regex.Replace(_strTarget, " ", "");
        //개행 처리
        string[] strTargetArr = _strTarget.Split(Environment.NewLine.ToCharArray(),
                                        StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < strTargetArr.Length; i++)
        {
            _strEncoTarget += EnFunc(strTargetArr[i], _password) + "\n";
        }
    }

    /// 
    /// 암호화
    /// 
    /// 
    /// 
    /// 
    private string EncryptString(string InputText, string Password)
    {

        // Rihndael class를 선언하고, 초기화
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        // 입력받은 문자열을 바이트 배열로 변환
        byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);

        // 딕셔너리 공격을 대비해서 키를 더 풀기 어렵게 만들기 위해서 
        // Salt를 사용한다.
        byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());

        // PasswordDeriveBytes 클래스를 사용해서 SecretKey를 얻는다.
        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

        // Create a encryptor from the existing SecretKey bytes.
        // encryptor 객체를 SecretKey로부터 만든다.
        // Secret Key에는 32바이트
        // (Rijndael의 디폴트인 256bit가 바로 32바이트입니다)를 사용하고, 
        // Initialization Vector로 16바이트
        // (역시 디폴트인 128비트가 바로 16바이트입니다)를 사용한다.
        ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

        // 메모리스트림 객체를 선언,초기화 
        MemoryStream memoryStream = new MemoryStream();

        // CryptoStream객체를 암호화된 데이터를 쓰기 위한 용도로 선언
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

        // 암호화 프로세스가 진행된다.
        cryptoStream.Write(PlainText, 0, PlainText.Length);

        // 암호화 종료
        cryptoStream.FlushFinalBlock();

        // 암호화된 데이터를 바이트 배열로 담는다.
        byte[] CipherBytes = memoryStream.ToArray();

        // 스트림 해제
        memoryStream.Close();
        cryptoStream.Close();

        // 암호화된 데이터를 Base64 인코딩된 문자열로 변환한다.
        string EncryptedData = Convert.ToBase64String(CipherBytes);

        // 최종 결과를 리턴
        return EncryptedData;
    }
    /// 
    /// 복호화
    /// 
    /// 
    /// 
    /// 
    private string DecryptString(string InputText, string Password)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        byte[] EncryptedData = Convert.FromBase64String(InputText);
        byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());

        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

        // Decryptor 객체를 만든다.
        ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream(EncryptedData);

        // 데이터 읽기(복호화이므로) 용도로 cryptoStream객체를 선언, 초기화
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

        // 복호화된 데이터를 담을 바이트 배열을 선언한다.
        // 길이는 알 수 없지만, 일단 복호화되기 전의 데이터의 길이보다는
        // 길지 않을 것이기 때문에 그 길이로 선언한다.
        byte[] PlainText = new byte[EncryptedData.Length];

        // 복호화 시작
        int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);

        memoryStream.Close();
        cryptoStream.Close();

        // 복호화된 데이터를 문자열로 바꾼다.
        string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);

        // 최종 결과 리턴
        return DecryptedData;
    }
}


반응형
Comments