본문 바로가기
C++ 200제/코딩 IT 정보

3DES 암호화 프로그램 소스, C#-자바(java)-안드로이드

by vicddory 2018. 4. 1.

3DES 암호화 프로그램 소스, C#-자바(java)-안드로이드


3DES 암호화 프로그램 소스, C#-자바(java)-안드로이드[triple des, C#, Java, Android]


출처 - Android: JAVA和C# 3DES加密解密 [링크]


형태가 유사한 3DES (triple des) 소스 코드입니다.

언어는 각각 C#, 자바, 안드로이드로 다르지만 형태는 거의 유사해 재밌네요.


C# 3DES 암호화 프로그램 소스


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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/// <Summary> 
/// DES3 encryption and decryption 
/// </ Summary> 3des 프로그램
public class Des3 
#region CBC mode ** 
 
/// <Summary> 
/// DES3 CBC mode encryption 
/// </ Summary> 
/// <Param name = "key"> key </ param> 
/// <Param name = "iv"> IV </ param> 
/// <Param name = "data"> byte array plaintext </ param> 
/// <Returns> byte array ciphertext </ returns> 
public static byte [] Des3EncodeCBC (byte [] key, byte [] iv, byte [] data) 
// Copy on MSDN 
 
try 
// Create a MemoryStream. 
MemoryStream mStream = new MemoryStream (); 
 
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider (); 
tdsp.Mode = CipherMode.CBC; // Default 
tdsp.Padding = PaddingMode.PKCS7; // Default 
 
// Create a CryptoStream using the MemoryStream 
// And the passed key and initialization vector (IV). 
CryptoStream cStream = new CryptoStream (mStream, 
tdsp.CreateEncryptor (key, iv), 
CryptoStreamMode.Write); 
 
// Write the byte array to the crypto stream and flush it. 
cStream.Write (data, 0, data.Length); 
cStream.FlushFinalBlock (); 
 
// Get an array of bytes from the 
// MemoryStream that holds the 
// Encrypted data. 
byte [] ret = mStream.ToArray (); 
 
// Close the streams. 
cStream.Close (); 
mStream.Close (); 
 
// Return the encrypted buffer. 
return ret; 
catch (CryptographicException e) 
Console.WriteLine ("A Cryptographic error occurred: {0}", e.Message); 
return null; 
 
/// <Summary> 
/// DES3 CBC mode decryption 
/// </ Summary> 
/// <Param name = "key"> key </ param> 
/// <Param name = "iv"> IV </ param> 
/// <Param name = "data"> byte array ciphertext </ param> 
/// <Returns> byte array plaintext </ returns> 
public static byte [] Des3DecodeCBC (byte [] key, byte [] iv, byte [] data) 
try 
// Create a new MemoryStream using the passed 
// Array of encrypted data. 
MemoryStream msDecrypt = new MemoryStream (data); 
 
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider (); 
tdsp.Mode = CipherMode.CBC; 
tdsp.Padding = PaddingMode.PKCS7; 
 
// Create a CryptoStream using the MemoryStream 
// And the passed key and initialization vector (IV). 
CryptoStream csDecrypt = new CryptoStream (msDecrypt, 
tdsp.CreateDecryptor (key, iv), 
CryptoStreamMode.Read); 
 
// Create buffer to hold the decrypted data. 
byte [] fromEncrypt = new byte
 
// Read the decrypted data out of the crypto stream 
// And place it into the temporary buffer. 
csDecrypt.Read (fromEncrypt, 0, fromEncrypt.Length); 
 
// Convert the buffer into a string and return it. 
return fromEncrypt; 
catch (CryptographicException e) 
Console.WriteLine ("A Cryptographic error occurred: {0}", e.Message); 
return null; 
 
#endregion 
 
#region ECB mode 
 
/// <Summary> 
/// DES3 ECB mode encryption 
/// </ Summary> 
/// <Param name = "key"> key </ param> 
/// <Param name = "iv"> IV (when the mode ECB, IV useless) </ param> 
/// <Param name = "str"> plaintext byte array </ param> 
/// <Returns> byte array ciphertext </ returns> 
public static byte [] Des3EncodeECB (byte [] key, byte [] iv, byte [] data) 
try 
// Create a MemoryStream. 
MemoryStream mStream = new MemoryStream (); 
 
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider (); 
tdsp.Mode = CipherMode.ECB; 
tdsp.Padding = PaddingMode.PKCS7; 
// Create a CryptoStream using the MemoryStream 
// And the passed key and initialization vector (IV). 
CryptoStream cStream = new CryptoStream (mStream, 
tdsp.CreateEncryptor (key, iv), 
CryptoStreamMode.Write); 
 
// Write the byte array to the crypto stream and flush it. 
cStream.Write (data, 0, data.Length); 
cStream.FlushFinalBlock (); 
 
// Get an array of bytes from the 
// MemoryStream that holds the 
// Encrypted data. 
byte [] ret = mStream.ToArray (); 
 
// Close the streams. 
cStream.Close (); 
mStream.Close (); 
 
// Return the encrypted buffer. 
return ret; 
catch (CryptographicException e) 
Console.WriteLine ("A Cryptographic error occurred: {0}", e.Message); 
return null; 
 
 
/// <Summary> 
/// DES3 ECB decryption mode 
/// </ Summary> 
/// <Param name = "key"> key </ param> 
/// <Param name = "iv"> IV (when the mode ECB, IV useless) </ param> 
/// <Param name = "str"> byte array ciphertext </ param> 
/// <Returns> byte array plaintext </ returns> 
public static byte [] Des3DecodeECB (byte [] key, byte [] iv, byte [] data) 
try 
// Create a new MemoryStream using the passed 
// Array of encrypted data. 
MemoryStream msDecrypt = new MemoryStream (data); 
 
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider (); 
tdsp.Mode = CipherMode.ECB; 
tdsp.Padding = PaddingMode.PKCS7; 
 
// Create a CryptoStream using the MemoryStream 
// And the passed key and initialization vector (IV). 
CryptoStream csDecrypt = new CryptoStream (msDecrypt, 
tdsp.CreateDecryptor (key, iv), 
CryptoStreamMode.Read); 
 
// Create buffer to hold the decrypted data. 
byte [] fromEncrypt = new byte
 
// Read the decrypted data out of the crypto stream 
// And place it into the temporary buffer. 
csDecrypt.Read (fromEncrypt, 0, fromEncrypt.Length); 
 
// Convert the buffer into a string and return it. 
return fromEncrypt; 
catch (CryptographicException e) 
Console.WriteLine ("A Cryptographic error occurred: {0}", e.Message); 
return null; 
 
#endregion 
 
/// <Summary> 
/// Class Testing 
/// </ Summary> 
public static void Test () 
System.Text.Encoding utf8 = System.Text.Encoding.UTF8; 
 
// Key is abcdefghijklmnopqrstuvwx of Base64 encoding 
byte [] key = Convert.FromBase64String ("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4"); 
byte [] iv = new byte [] {12345678}; // When the mode when the ECB, IV useless 
byte [] data = utf8.GetBytes ("China ABCabc123"); 
 
System.Console.WriteLine ("ECB mode:"); 
byte [] str1 = Des3.Des3EncodeECB (key, iv, data); 
byte [] str2 = Des3.Des3DecodeECB (key, iv, str1); 
System.Console.WriteLine (Convert.ToBase64String (str1)); 
System.Console.WriteLine (System.Text.Encoding.UTF8.GetString (str2)); 
 
System.Console.WriteLine (); 
 
System.Console.WriteLine ("CBC mode:"); 
byte [] str3 = Des3.Des3EncodeCBC (key, iv, data); 
byte [] str4 = Des3.Des3DecodeCBC (key, iv, str3); 
System.Console.WriteLine (Convert.ToBase64String (str3)); 
System.Console.WriteLine (utf8.GetString (str4)); 
 
System.Console.WriteLine (); 
 
 
cs

자바 java 3DES 암호화 프로그램 소스


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
import java.security.Key; 
 
import javax.crypto.Cipher; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.DESedeKeySpec; 
import javax.crypto.spec.IvParameterSpec; 
 
import sun.misc.BASE64Decoder; 
import sun.misc.BASE64Encoder; 
 
public class Des3 { 
public static void main (String [] args) throws Exception { 
 
byte [] key = new BASE64Decoder () decodeBuffer ("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4").; 
byte [] keyiv = {12345678}; 
 
byte [] data = "China ABCabc123" .getBytes ("UTF-8"); 
 
System.out.println ("ECB encryption and decryption"); 
byte [] str3 = des3EncodeECB (key, data); 
byte [] str4 = ees3DecodeECB (key, str3); 
System.out.println (new BASE64Encoder () encode (str3).); 
System.out.println (new String (str4, "UTF-8")); 
 
System.out.println (); 
 
System.out.println ("CBC encryption and decryption"); 
byte [] str5 = des3EncodeCBC (key, keyiv, data); 
byte [] str6 = des3DecodeCBC (key, keyiv, str5); 
System.out.println (new BASE64Encoder () encode (str5).); 
System.out.println (new String (str6, "UTF-8")); 
 
 
/ ** 
* ECB encryption, not IV 
*param Key Key 
*param Data in plain text 
*return Base64-encoded ciphertext 
*throws Exception 3des 프로그램
* / 
public static byte [] des3EncodeECB (byte [] key, byte [] data) 
throws Exception { 
 
Key deskey = null; 
DESedeKeySpec spec = new DESedeKeySpec (key); 
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance ("desede"); 
deskey = keyfactory.generateSecret (spec); 
 
Cipher cipher = Cipher.getInstance ("desede" + "/ ECB / PKCS5Padding"); 
 
cipher.init (Cipher.ENCRYPT_MODE, deskey); 
byte [] bOut = cipher.doFinal (data); 
 
return bOut; 
 
/ ** 
* ECB decryption, not IV 
*param Key Key 
*param Data Base64 encoded ciphertext 
*return Plaintext 
*throws Exception 
* / 
public static byte [] ees3DecodeECB (byte [] key, byte [] data) 
throws Exception { 
 
Key deskey = null; 
DESedeKeySpec spec = new DESedeKeySpec (key); 
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance ("desede"); 
deskey = keyfactory.generateSecret (spec); 
 
Cipher cipher = Cipher.getInstance ("desede" + "/ ECB / PKCS5Padding"); 
 
cipher.init (Cipher.DECRYPT_MODE, deskey); 
 
byte [] bOut = cipher.doFinal (data); 
 
return bOut; 
 
 
/ ** 
* CBC encryption 
*param Key Key 
*param Keyiv IV 
*param Data in plain text 
*return Base64-encoded ciphertext 
*throws Exception 
* / 
public static byte [] des3EncodeCBC (byte [] key, byte [] keyiv, byte [] data) 
throws Exception { 
 
Key deskey = null; 
DESedeKeySpec spec = new DESedeKeySpec (key); 
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance ("desede"); 
deskey = keyfactory.generateSecret (spec); 
 
Cipher cipher = Cipher.getInstance ("desede" + "/ CBC / PKCS5Padding"); 
IvParameterSpec ips = new IvParameterSpec (keyiv); 
cipher.init (Cipher.ENCRYPT_MODE, deskey, ips); 
byte [] bOut = cipher.doFinal (data); 
 
return bOut; 
 
/ ** 
* CBC decryption 
*param Key Key 
*param Keyiv IV 
*param Data Base64 encoded ciphertext 
*return Plaintext 
*throws Exception 
* / 
public static byte [] des3DecodeCBC (byte [] key, byte [] keyiv, byte [] data) 
throws Exception { 
 
Key deskey = null; 
DESedeKeySpec spec = new DESedeKeySpec (key); 
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance ("desede"); 
deskey = keyfactory.generateSecret (spec); 
 
Cipher cipher = Cipher.getInstance ("desede" + "/ CBC / PKCS5Padding"); 
IvParameterSpec ips = new IvParameterSpec (keyiv); 
 
cipher.init (Cipher.DECRYPT_MODE, deskey, ips); 
 
byte [] bOut = cipher.doFinal (data); 
 
return bOut; 
 
 
cs

위의 자바나 아래의 안드로이드 소스 모두 호환이 가능합니다.


다만, 안드로이드는 기본 라이브러리에 암호화 부분이 있어 자바보단 다루기 쉬워요.

안드로이드로 코딩하신다면 자바 소스를 그대로 사용하지 마시고 기본 라이브러를 사용하세요.


안드로이드 3DES 암호화 프로그램 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main (String [] args) throws Exception { // 3des 프로그램
 
    byte [] key = Base64.decode ("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4". getBytes (), Base64.DEFAULT); 
    byte [] keyiv = {12345678}; 
 
    byte [] data = "China ABCabc123". getBytes ("UTF-8"); 
 
    System.out.println ("ECB encryption and decryption"); 
    byte [] str3 = des3EncodeECB (key, data); 
    byte [] str4 = ees3DecodeECB (key, str3); 
    System.out.println (new String (Base64.encode (str3, Base64.DEFAULT), "UTF-8")); 
    System.out.println (new String (str4, "UTF-8")); 
 
    System.out.println (); 
 
    System.out.println ("CBC encryption and decryption"); 
    byte [] str5 = des3EncodeCBC (key, keyiv, data); 
    byte [] str6 = des3DecodeCBC (key, keyiv, str5); 
    System.out.println (new String (Base64.encode (str5, Base64.DEFAULT), "UTF-8")); 
    System.out.println (new String (str6, "UTF-8")); 
cs


안드로이드는 위와 같이 Base64 패키지를 별도로 필요합니다.


만약 컴파일 시, 패키지를 제대로 로딩하지 못한다면, Bouncy Castle처럼 강제로 해당 패키지를 프로젝트에 삽입해 해결할 수 있습니다.


3DES 암호화 프로그램 소스[triple des, C#, Java, Android]


Android Bouncycastle에 대한 자세한 정보는 아래 링크에 있습니다.



이 포스트에선 3DES 알고리즘은 다루지 않았는데, 해당 알고리즘 정보는 웹상에 많으니 다른 분의 포스트를 참고해주세요. 이 포스트를 통해선 소스만 봐주세요.


< 암호화 정보 더 알아보기 >


1. Trusted Platform Module, 스마트폰 보안 기술 TPM 설명, 신뢰 플랫폼 모듈 [링크]

2. C# 3DES 암호화와 복호화 소스 [링크]


3DES 암호화 프로그램 소스, C#-자바(java)-안드로이드

댓글