[OS/UBUNTU] openssl 명령 : AES 복호화 파일 생성하기
■ openssl 명령을 사용해 AES 복호화 파일을 생성하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2. [터미널]에서
■ openssl 명령을 사용해 AES 복호화 파일을 생성하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2. [터미널]에서
■ openssl 명령을 사용해 AES 암호화 파일 생성하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2. [터미널]에서
■ openssl 명령을 사용해 AES 암호화 파일을 생성하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2. [터미널]에서
■ AES 암호화 도구를 만드는 방법을 보여준다. ▶ Cargo.toml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[package] name = "test_project" version = "0.1.0" edition = "2021" [dependencies] aes = "0.7.5" block-modes = "0.8.1" base64 = "0.13.0" sha2 = "0.9.8" getrandom = "0.2.3" |
▶ src/cipher.rs
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 |
use aes; use block_modes; use block_modes::block_padding; use block_modes::BlockMode; use sha2; use sha2::Digest; type AesCbc = block_modes::Cbc<aes::Aes256, block_padding::Pkcs7>; const SALT : &str = "LFsMH#kL!IfY:dcEz9F/dvj17nUN"; pub fn encrypt(plain_text : &str, password : &str, initial_value_byte_vector : &Vec<u8>) -> String { let key_byte_vector : Vec<u8> = get_key_byte_vector(password); let cbc : block_modes::Cbc<aes::Aes256, block_padding::Pkcs7> = AesCbc::new_from_slices(&key_byte_vector, &initial_value_byte_vector).unwrap(); let encrypted_byte_vector : Vec<u8> = cbc.encrypt_vec(plain_text.as_bytes()); let encrypted_text : String = base64::encode(encrypted_byte_vector); return encrypted_text; } pub fn decrypt(encrypted_text : &str, password : &str, initial_value_byte_vector : &Vec<u8>) -> String { let key_byte_vector : Vec<u8> = get_key_byte_vector(password); let encrypted_byte_vector : Vec<u8> = base64::decode(encrypted_text).unwrap(); let cbc : block_modes::Cbc<aes::Aes256, block_padding::Pkcs7> = AesCbc::new_from_slices(&key_byte_vector, initial_value_byte_vector).unwrap(); let plain_byte_vector : Vec<u8> = cbc.decrypt_vec(&encrypted_byte_vector).unwrap(); return String::from_utf8(plain_byte_vector).unwrap(); } fn get_key_byte_vector(password : &str) -> Vec<u8> { let password_salt : String = format!("{}::{}", password, SALT); let mut sha256 : sha2::Sha256 = sha2::Sha256::new(); sha256.update(password_salt.as_bytes()); return sha256.finalize().to_vec(); } pub fn get_initial_value_byte_vector() -> Vec<u8> { let mut initial_value_byte_vector : Vec<u8> = vec! [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; getrandom::getrandom(&mut initial_value_byte_vector).unwrap(); return initial_value_byte_vector; } |
▶ src/main.rs
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 |
use std::env; mod cipher; fn main() { let argument_vector : Vec<String> = env::args().collect(); if argument_vector.len() < 4 { print_usage_message(); return; } let method : String = String::from(argument_vector[1].trim()); let password : String = String::from(argument_vector[2].trim()); let source : String = String::from(argument_vector[3].trim()); let initial_value_byte_vector : Vec<u8> = cipher::get_initial_value_byte_vector(); let target : String = match &method[..] { "enc" => cipher::encrypt(&source, &password, &initial_value_byte_vector), "dec" => cipher::decrypt(&source, &password, &initial_value_byte_vector), _ => { print_usage_message(); return; } }; println!("{}", target); } fn print_usage_message() { println!("[USAGE] test_project (enc|dec) password source"); } |
test_project.zip
■ aes 크레이트를 설치하는 방법을 보여준다. ▶ Cargo.toml
1 2 3 4 5 6 |
... [dependencies] aes = "0.7.5" |
■ AesCryptoServiceProvider 클래스를 사용해 암호화/복호화하는 방법을 보여준다. ▶ SecurityHelper.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 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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace TestProject { /// <summary> /// 보안 헬퍼 /// </summary> public static class SecurityHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// RNG 암호 서비스 공급자 /// </summary> private static RNGCryptoServiceProvider _provider = new RNGCryptoServiceProvider(); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 문자열로 암호화하기 - EncryptToString(source, password, salt) /// <summary> /// 문자열로 암호화하기 /// </summary> /// <param name="source">소스 문자열</param> /// <param name="password">패스워드</param> /// <param name="salt">솔트</param> /// <returns>암호화 문자열</returns> public static string EncryptToString(string source, string password, string salt) { return GetHexadecimalString(Encrypt(source, password, salt)); } #endregion #region 문자열에서 복호화하기 - DecryptFromString(source, password, salt) /// <summary> /// 문자열에서 복호화하기 /// </summary> /// <param name="source">소스 문자열</param> /// <param name="password">패스워드</param> /// <param name="salt">솔트</param> /// <returns>복호화 문자열</returns> public static string DecryptFromString(string source, string password, string salt) { return Decrypt(GetByteArrayFromHexadecimalString(source), password, salt); } #endregion #region 임의 정수 값 구하기 - GetRandomIntegerValue(minimumValue, maximumValue) /// <summary> /// 임의 정수 값 구하기 /// </summary> /// <param name="minimumValue">최소 값</param> /// <param name="maximumValue">최대 값</param> /// <returns>임의 정수 값</returns> public static int GetRandomIntegerValue(int minimumValue, int maximumValue) { uint scale = uint.MaxValue; while(scale == uint.MaxValue) { byte[] byteArray = new byte[4]; _provider.GetBytes(byteArray); scale = BitConverter.ToUInt32(byteArray, 0); } return (int)(minimumValue + (maximumValue - minimumValue) * (scale / (double)uint.MaxValue)); } #endregion #region 임의 솔트 구하기 - GetRandomSalt() /// <summary> /// 임의 솔트 구하기 /// </summary> /// <returns>임의 솔트</returns> public static string GetRandomSalt() { int byteArrayLength = GetRandomIntegerValue(10, 20); byte[] saltByteArray = new byte[byteArrayLength]; _provider.GetBytes(saltByteArray); return GetHexadecimalString(saltByteArray); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 16진수 문자열에서 바이트 배열 구하기 - GetByteArrayFromHexadecimalString(source) /// <summary> /// 16진수 문자열에서 바이트 배열 구하기 /// </summary> /// <param name="source">소스 문자여</param> /// <returns>바이트 배열</returns> private static byte[] GetByteArrayFromHexadecimalString(string source) { source = source.Replace(" ", string.Empty); int byteCount = source.Length / 2; byte[] targetByteArray = new byte[byteCount]; for(int i = 0; i < byteCount; i++) { targetByteArray[i] = Convert.ToByte(source.Substring(2 * i, 2), 16); } return targetByteArray; } #endregion #region 16진수 문자열 구하기 - GetHexadecimalString(sourceByteArray) /// <summary> /// 16진수 문자열 구하기 /// </summary> /// <param name="sourceByteArray">소스 바이트 배열</param> /// <returns>16진수 문자열</returns> private static string GetHexadecimalString(byte[] sourceByteArray) { string target = string.Empty; foreach(byte sourceByte in sourceByteArray) { target += " " + sourceByte.ToString("X2"); } if(target.Length > 0) { target = target.Substring(1); } return target; } #endregion #region 키/초기 값 만들기 - MakeKeyAndInitialValue(password, saltByteArray, keySizeBitCount, blockSizeBitCount, keyByteArray, initialValueByteArray) /// <summary> /// 키/초기 값 만들기 /// </summary> /// <param name="password">패스워드</param> /// <param name="saltByteArray">솔트 바이트 배열</param> /// <param name="keySizeBitCount">키 크기 비트 카운트</param> /// <param name="blockSizeBitCount">블럭 크기 비트 카운트</param> /// <param name="keyByteArray">키 바이트 배열</param> /// <param name="initialValueByteArray">초기 값 바이트 배열</param> private static void MakeKeyAndInitialValue ( string password, byte[] saltByteArray, int keySizeBitCount, int blockSizeBitCount, ref byte[] keyByteArray, ref byte[] initialValueByteArray ) { Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltByteArray, 513); keyByteArray = rfc2898DeriveBytes.GetBytes(keySizeBitCount / 8); initialValueByteArray = rfc2898DeriveBytes.GetBytes(blockSizeBitCount / 8); } #endregion #region 암호화/복호화하기 - EncryptOrDecrypt(password, sourceByteArray, salt, encrypt) /// <summary> /// 암호화/복호화하기 /// </summary> /// <param name="password">패스워드</param> /// <param name="sourceByteArray">소스 바이트 배열</param> /// <param name="salt">솔트</param> /// <param name="encrypt">암호화 여부</param> /// <returns>암호화/복호화 바이트 배열</returns> private static byte[] EncryptOrDecrypt(string password, byte[] sourceByteArray, string salt, bool encrypt) { AesCryptoServiceProvider provider = new AesCryptoServiceProvider(); int keySizeBitCount = 0; for(int i = 1024; i >= 1; i--) { if(provider.ValidKeySize(i)) { keySizeBitCount = i; break; } } int blockSizeBitCount = provider.BlockSize; byte[] saltByteArray = GetByteArrayFromHexadecimalString(salt); byte[] keyByteArray = null; byte[] initialValueByteArray = null; MakeKeyAndInitialValue(password, saltByteArray, keySizeBitCount, blockSizeBitCount, ref keyByteArray, ref initialValueByteArray); ICryptoTransform cryptoTransform; if(encrypt) { cryptoTransform = provider.CreateEncryptor(keyByteArray, initialValueByteArray); } else { cryptoTransform = provider.CreateDecryptor(keyByteArray, initialValueByteArray); } MemoryStream targetStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(targetStream, cryptoTransform, CryptoStreamMode.Write); cryptoStream.Write(sourceByteArray, 0, sourceByteArray.Length); try { cryptoStream.FlushFinalBlock(); } catch(CryptographicException) { } catch { throw; } byte[] targetByteArray = targetStream.ToArray(); try { cryptoStream.Close(); } catch(CryptographicException) { } catch { throw; } targetStream.Close(); return targetByteArray; } #endregion #region 암호화하기 - Encrypt(source, password, salt) /// <summary> /// 암호화하기 /// </summary> /// <param name="source">소스 문자열</param> /// <param name="password">패스워드</param> /// <param name="salt">솔트</param> /// <returns>암호화 바이트 배열</returns> private static byte[] Encrypt(string source, string password, string salt) { UTF8Encoding encoding = new UTF8Encoding(); byte[] sourceByteArray = encoding.GetBytes(source); return EncryptOrDecrypt(password, sourceByteArray, salt, true); } #endregion #region 복호화하기 - Decrypt(sourceByteArray, password, salt) /// <summary> /// 복호화하기 /// </summary> /// <param name="sourceByteArray">소스 바이트 배열</param> /// <param name="password">패스워드</param> /// <param name="salt">솔트</param> /// <returns>복호화 문자열</returns> private static string Decrypt(byte[] sourceByteArray, string password, string salt) { byte[] targetByteArray = EncryptOrDecrypt(password, sourceByteArray, salt, false); UTF8Encoding encoding = new UTF8Encoding(); return new string(encoding.GetChars(targetByteArray)); } #endregion } } |
▶ Program.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 |
using System; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { string plainText = "무궁화 꽃이 피었습니다."; string password = "test"; string salt = SecurityHelper.GetRandomSalt(); string textEncrypted = SecurityHelper.EncryptToString(plainText, password, salt); string textDecrypted = SecurityHelper.DecryptFromString(textEncrypted, password, salt); Console.WriteLine($"평문 : {plainText}"); Console.WriteLine($"패스워드 : {password}"); Console.WriteLine($"솔트 : {salt}"); Console.WriteLine($"암호문 : {textEncrypted}"); Console.WriteLine($"복호문 : {textDecrypted}"); } #endregion } } |
TestProject.zip
■ RijndaelManaged 클래스를 사용해 대칭키 암호화하는 방법을 보여준다. ▶ MainForm.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 |
using System; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.processButton.Click += processButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 암복호화 버튼 클릭시 처리하기 - processButton_Click(sender, e) /// <summary> /// 암복호화 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void processButton_Click(object sender, EventArgs e) { string cipherText = AESHelper.Encrypt(this.plainTextTextBox.Text, this.passwordTextBox.Text); this.cipherTextTextBox.Text = cipherText; string plainText = AESHelper.Decrypt(cipherText, this.passwordTextBox.Text); this.resultTextTextBox.Text = plainText; } #endregion } } |
▶ AESHelper.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 |
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace TestProject { /// <summary> /// AES 헬퍼 /// </summary> public class AESHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 암호화 하기 - Encrypt(plainText, password) /// <summary> /// 암호화 하기 /// </summary> /// <param name="plainText">평문 텍스트</param> /// <param name="password">패스워드</param> /// <returns>암호화 텍스트</returns> public static string Encrypt(string plainText, string password) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); byte[] saltArray = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] plaintTextArray = Encoding.Unicode.GetBytes(plainText); Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltArray, 100); ICryptoTransform cryptoTransform = rijndaelManaged.CreateEncryptor(rfc2898DeriveBytes.GetBytes(32), rfc2898DeriveBytes.GetBytes(16)); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write); cryptoStream.Write(plaintTextArray, 0, plaintTextArray.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextArray = memoryStream.ToArray(); string cipherText = Convert.ToBase64String(cipherTextArray); memoryStream.Close(); cryptoStream.Close(); return cipherText; } #endregion #region 복호화 하기 - Decrypt(cipherText, password) /// <summary> /// 복호화 하기 /// </summary> /// <param name="cipherText">암호화 텍스트</param> /// <param name="password">패스워드</param> /// <returns>평문 텍스트</returns> public static string Decrypt(string cipherText, string password) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); byte[] saltArray = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] cipherTextArray = Convert.FromBase64String(cipherText); byte[] plainTextArray = new byte[cipherTextArray.Length]; Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltArray, 100); ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor(rfc2898DeriveBytes.GetBytes(32), rfc2898DeriveBytes.GetBytes(16)); MemoryStream memoryStream = new MemoryStream(cipherTextArray); CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read); int plainTextCount = cryptoStream.Read(plainTextArray, 0, plainTextArray.Length); string plainText = Encoding.Unicode.GetString(plainTextArray, 0, plainTextCount); memoryStream.Close(); cryptoStream.Close(); return plainText; } #endregion } } |
TestProject.zip