암호화하여 직렬화, 복호화하여 역직렬화 [문제해결중]

C#/Problems 2019. 4. 10. 03:26



BinaryFormatter와 FileStream을 이용하여 Serialize, Deserialize까지는 무난하게 구현했다.

후에 AES-128 암호화 방식을 이용하여 암호화된 값으로 직렬화를 하고, 복호화를 이용하여 역직렬화해서 파일로는 값을 못보고, 내부에서만 사용할 수 있게끔 만드려고 했다.

처음에는 AES-128을 API를 이용하지 않고 구현하려고 했으나, AES 알고리즘 과정 중 SubByte(State Array의 값들을 S-Box의 값과 치환하는 과정)에서 막혀서 API를 이용했다.

암호화까지에는 성공했으나, 복호화 과정에서 지속적으로 스트림에서 오류가 발생했다.

위처럼 Deserialize하는 스트림이 계속 비어있다고 뜨는데, 도무지 해답을 찾지 못하겠다. (이건 아마 내가 Stream에 대한 지식이 부족한 것 같다)

국내 사이트부터 외국 사이트, Docs, 논문 다 봤는데 모르겠다.


string형으로도 받아보고, byte[]형으로도 받아보려했으나, 자꾸 저 에러가 뜬다.

내일은 stream 공부 더해보고 오류 수정해야겠다. 이젠 진짜 자야겠다.

내일 늦으면 안되는데




AES만드려고 작성하던 Backup.cs

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
 
namespace TestMin
{
    public static class Backup
    {
        //Serialize Method
        public static bool Serialize<T>(T obj, string path)
        {
            if (obj == null)
            {
                return false;
            }
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            FileStream fileStream = new FileStream(path, FileMode.Create);
            binaryFormatter.Serialize(fileStream, obj);
            fileStream.Close();
            return true;
        }
 
        //Deserialize Method
        public static T Deserialize<T>(string path)
        {
            var isExists = File.Exists(path);
            if (isExists)
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                FileStream fileStream = new FileStream(path, FileMode.Open);
                var temp = binaryFormatter.Deserialize(fileStream);
                fileStream.Close();
                return (T)temp;
            }
            else
            {
                return default(T);
            }
        }
 
        //AES-256 Encryption
        public static void EncryptionToAES<T>(T obj)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            binaryFormatter.Serialize(memoryStream, obj);
            byte[,] keyArr = new byte[44]
            {
                {0x540x4B0x200x53 },
                {0x480x490x4D0x45 },
                {0x450x4E0x490x4F },
                {0x200x470x4E0x4B }
            };
            var plainText = memoryStream.ToArray();
            byte[,] stateArr = new byte[44]
            {
                {plainText[0], plainText[4], plainText[8], plainText[12] },
                {plainText[1], plainText[5], plainText[9], plainText[13] },
                {plainText[2], plainText[6], plainText[10], plainText[14] },
                {plainText[3], plainText[7], plainText[11], plainText[15] }
            };
        }
 
        //State sub S-Box
        public static void SubByte()
        {
 
        }
 
        //Take Round Key
        public static void KeyExpansion()
        {
 
        }
 
        //ShiftRow
        public static void ShiftRow(byte[] state)
        {
            for (int row = 1; row < 4; row++//row1 ~ row3
            {
                //byte[1] temp 
            }
        }
 
        public static void KeySchedule()
        {
            //4의 배수
            //Key 4열 추출
 
            //1칸 Shift
 
            //S-Box와 치환
 
            //Key+1열에서 -4열 추출
 
            //-4열 XOR 치환열 XOR RCON
 
        }
 
        public static void MixColumn()
        {
            //(a(0,0)*02) XOR (a(1,0)*03) XOR (a(2,0)*01) XOR (a(3,0)*01)
        }
    }
}
 
cs




직렬화, 역직렬화, 암호화, 복호화

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Runtime.Serialization;
 
namespace TestMin
{
    public static class Minseok
    {
        //Serialize Method
        public static bool Serialize<T>(T obj, string path)
        {
            if (obj == null)
            {
                return false;
            }
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            FileStream fileStream = new FileStream(path, FileMode.Create);
            binaryFormatter.Serialize(fileStream, obj);
            fileStream.Close();
            return true;
        }
 
        //Deserialize Method
        public static T Deserialize<T>(string path)
        {
            var isExists = File.Exists(path);
            if (isExists)
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                FileStream fileStream = new FileStream(path, FileMode.Open);
                var temp = binaryFormatter.Deserialize(fileStream);
                fileStream.Close();
                return (T)temp;
            }
            else
            {
                return default(T);
            }
        }
 
        //AES-128 Encryption
        public static byte[] EncryptionToAES<T>(T obj)
        {
            //Key
            byte[] keyArr = new byte[] { 0x540x480x450x200x4B0x490x4E0x470x200x4D0x490x4E0x530x450x4F0x4b };
 
            //Convert obj to byte array
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            binaryFormatter.Serialize(memoryStream, obj);
            var plainArr = memoryStream.ToArray();
            memoryStream.Close();
 
            //Initialization Vector (IV 생성)
            byte[] iV = Encoding.UTF8.GetBytes("THEJOEUNCOMPUTER");
 
            //Encryption
            Aes aes = Aes.Create();
            aes.KeySize = 128;
            aes.Key = keyArr;
            aes.Padding = PaddingMode.PKCS7; //padding 방법
            aes.IV = iV; //대칭 Vector = default Vector
            ICryptoTransform aesForm = aes.CreateEncryptor(aes.Key, aes.IV); //암호화 기본 작업 인터페이스 변수에 Key, Iv를 가진 암호화 개체 생성
            MemoryStream enMemoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(enMemoryStream, aesForm, CryptoStreamMode.Write);
            StreamWriter streamWriter = new StreamWriter(cryptoStream);
            streamWriter.Write(plainArr);
            byte[] chiperArr = enMemoryStream.ToArray();
            enMemoryStream.Close();
 
            return chiperArr;
        }
 
        //AES-128 Decryption
        public static T DecryptionByte<T>(byte[] chiperArr)
        {
            //Key
            byte[] keyArr = new byte[] { 0x540x480x450x200x4B0x490x4E0x470x200x4D0x490x4E0x530x450x4F0x4b };
 
            ////Convert obj to byte array
            //BinaryFormatter binaryFormatter = new BinaryFormatter();
            //MemoryStream memoryStream = new MemoryStream();
            //binaryFormatter.Serialize(memoryStream, obj);
            //var plainArr = memoryStream.ToArray();
            //memoryStream.Close();
 
            //Initialization Vector (IV 생성)
            byte[] iV = Encoding.UTF8.GetBytes("THEJOEUNCOMPUTER");
 
            //Decryption
            Aes aes = Aes.Create();
            aes.KeySize = 128;
            aes.Key = keyArr;
            aes.Padding = PaddingMode.PKCS7; //padding 방법
            aes.IV = iV; //대칭 Vector = default Vector
 
            ICryptoTransform dcryp = aes.CreateDecryptor(aes.Key, aes.IV);
            MemoryStream ms = new MemoryStream();
            CryptoStream decrypStream = new CryptoStream(ms, dcryp, CryptoStreamMode.Write);
            decrypStream.Write(chiperArr, 0, chiperArr.Length);
            decrypStream.FlushFinalBlock();
 
            ms.Position = 0;
            byte[] temp = new byte[ms.Length];
            ms.Read(temp, 0, temp.Length);
            ms.Close();
 
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream ms2 = new MemoryStream(temp, 0, temp.Length);
            formatter.Deserialize(ms2);
 
            return (T)temp;
            
 
            //ICryptoTransform cryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV); //암호화 기본 작업 인터페이스 변수에 Key, Iv를 가진 복호화 개체 생성
            //MemoryStream memoryStream = new MemoryStream(chiperArr);
            //CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read);
            //StreamReader streamReader = new StreamReader(cryptoStream);
            //MemoryStream memory2 = new MemoryStream();
            //memory2.Write()
            //var ICustomFormatter = new BinaryFormatter();
            //ICustomFormatter.Deserialize(streamReader);
            //var plainObject = streamReader.ReadToEnd();
 
            //ICryptoTransform descrypt = aes.CreateDecryptor(aes.Key, aes.IV);
            //MemoryStream ms1 = new MemoryStream(chiperArr);
            //CryptoStream cryptoStream = new CryptoStream(ms1, descrypt, CryptoStreamMode.Read);
            //byte[] temp = new byte[chiperArr.Length];
            //cryptoStream.Write(temp, 0, temp.Length);
            //StreamReader ms1Reader = new StreamReader(cryptoStream);
            //ms1Reader.
            //StreamWriter ms1Writer = new StreamWriter(cryptoStream);
            //ms1Writer.Write(chiperArr);
 
            //ms1.Read(temp, 0, temp.Length);
            //MemoryStream ms2 = new MemoryStream(temp);
            //ms2.Write(temp, 0, temp.Length);
 
            //IFormatter formatter = new BinaryFormatter();
            //ms2.Seek(0, SeekOrigin.Begin);
            //T obj = (T)formatter.Deserialize(ms1);
 
            //return obj;
        }
    }
}
 
cs





'C# > Problems' 카테고리의 다른 글

멀티스레딩 + SetCursorPosition에서 생긴 문제 [해결]  (0) 2019.04.01
하는중  (0) 2019.04.01
공부할 것과 정리중인 것  (0) 2019.03.28
공부중  (0) 2019.03.27
Console.Read() 의 형변환 [해결]  (0) 2019.03.25
: