다운로드 데이터 반환과 암호화 추가

This commit is contained in:
김판돌 2023-11-24 22:02:26 +09:00
parent ed1f226c8a
commit 4e940ba8ec
12 changed files with 357 additions and 31 deletions

View File

@ -8,12 +8,11 @@ namespace Server.Git
{ {
public abstract class AbstractGit public abstract class AbstractGit
{ {
public Crypto crypto = new Crypto();
private static readonly NLog.ILogger logger = LogManager.GetCurrentClassLogger(); private static readonly NLog.ILogger logger = LogManager.GetCurrentClassLogger();
public bool isRestart; public bool isRestart;
string _repositoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "excel"); string _repositoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "excel");
public string excel = "";
public string repositoryPath { get { return _repositoryPath; } } public string repositoryPath { get { return _repositoryPath; } }
/// <summary> /// <summary>
@ -26,10 +25,10 @@ namespace Server.Git
Pull(); Pull();
if (isRestart) if (isRestart)
goto restart; goto restart;
ChangeScript(); string excel = ChangeScript();
if (isRestart) if (isRestart)
goto restart; goto restart;
Push(); Push(excel);
if (isRestart) if (isRestart)
goto restart; goto restart;
} }
@ -37,7 +36,7 @@ namespace Server.Git
/// <summary> /// <summary>
/// 엑셀 불러오기, 저장, 혹은 배포 까지 작업해야하는 함수 /// 엑셀 불러오기, 저장, 혹은 배포 까지 작업해야하는 함수
/// </summary> /// </summary>
public abstract void ChangeScript(); public abstract string ChangeScript();
private void Pull() private void Pull()
{ {
@ -81,7 +80,7 @@ namespace Server.Git
} }
} }
private void Push() private void Push(string excel)
{ {
if(excel == "") if(excel == "")
{ {
@ -89,13 +88,16 @@ namespace Server.Git
} }
//json 저장 //json 저장
using (StreamWriter writer = new StreamWriter(repositoryPath + @"\excel.json")) using (StreamWriter writer = new StreamWriter(repositoryPath + @"/excel.json"))
{ {
writer.Write(excel); writer.Write(excel);
Console.WriteLine($"save file : {repositoryPath + @"\excel.json"}"); Console.WriteLine($"save file : {repositoryPath + @"/excel.json"}");
} }
//이곳에서 json변경후 저장
//압축
//string EncryptoExcel = crypto.Compress(excel);
//암호화
ProtocolProcessor.cryptoData = crypto.Compress(excel);
// 스테이징 // 스테이징
RepositorySet("add .", repositoryPath); RepositorySet("add .", repositoryPath);

View File

@ -6,7 +6,7 @@ namespace Server.Git
{ {
public class XlsxToJson : AbstractGit public class XlsxToJson : AbstractGit
{ {
public override void ChangeScript() public override string ChangeScript()
{ {
//저장경로 : repositoryPath //저장경로 : repositoryPath
//작업할것 //작업할것
@ -30,11 +30,9 @@ namespace Server.Git
else else
{ {
Console.WriteLine("-1 : NotUpdate"); Console.WriteLine("-1 : NotUpdate");
return; return "";
} }
} }
excel = JsonConvert.SerializeObject(sheetList);
//현재 서버는 PostgreSQL기준으로 쿼리를 생성하는 코드와 패키지가 세팅되어 있습니다 이점 참고바랍니다 //현재 서버는 PostgreSQL기준으로 쿼리를 생성하는 코드와 패키지가 세팅되어 있습니다 이점 참고바랍니다
//추가로 해당 기능을 사용하려면 서버에 excel이라는 스키마가 존재하여야 합니다. //추가로 해당 기능을 사용하려면 서버에 excel이라는 스키마가 존재하여야 합니다.
if (sheets != null) if (sheets != null)
@ -42,7 +40,7 @@ namespace Server.Git
ExcelSQL sql = new ExcelSQL(sheets); ExcelSQL sql = new ExcelSQL(sheets);
sql.DataUpdate(); sql.DataUpdate();
} }
return JsonConvert.SerializeObject(sheetList);
} }
} }
} }

View File

@ -0,0 +1,52 @@
using Server.System;
using Newtonsoft.Json;
using Server.Git;
namespace Server.Service
{
public class Downlode : AbstractService
{
private DownlodeReq req;
public override string Process()
{
//버전 확인후 암호화된 데이터를 내려주거나 아예 반환을 하지 않음.
if (req.version == ProtocolProcessor.version)
return makeResp("");
return makeResp(ProtocolProcessor.cryptoData);
}
public override Protocol ProtocolValue() => Protocol.Downlode;
public override Req Requst(string json)
{
req = JsonConvert.DeserializeObject<DownlodeReq>(json);
return req;
}
private string makeResp(string data)
{
DownlodeResp resp = new DownlodeResp();
resp.data = data;
resp.status = 200;
return resp.ToJson();
}
}
public class DownlodeReq : Req
{
public string version;
public override bool IsReceivedAllField()
{
if (version == "")
return false;
return true;
}
}
public class DownlodeResp : Resp
{
public string data;
}
}

View File

@ -9,8 +9,13 @@ namespace Server.System
public abstract string Process(); public abstract string Process();
public abstract Req Requst(string json); public abstract Req Requst(string json);
public Crypto crypto = new Crypto();
} }
/// <summary>
/// 입력 요청 데이터
/// </summary>
public abstract class Req public abstract class Req
{ {
public Protocol cmd; public Protocol cmd;
@ -21,6 +26,9 @@ namespace Server.System
} }
} }
/// <summary>
/// 반환 데이터
/// </summary>
public abstract class Resp public abstract class Resp
{ {
public int status; public int status;

260
Server/System/Crypto.cs Normal file
View File

@ -0,0 +1,260 @@
using System;
using System.IO.Compression;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Crypto
{
private const string str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>
/// 압축
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public string Compress(string text)
{
byte[] uniBytes = Encoding.Unicode.GetBytes(text);
byte[] compressedByte;
using (MemoryStream ms = new MemoryStream())
{
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress))
{
ds.Write(uniBytes, 0, uniBytes.Length);
}
compressedByte = ms.ToArray();
}
return Convert.ToBase64String(compressedByte);
}
/// <summary>
/// 압축해제
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public string Decompress(string text)
{
MemoryStream resultStream = new MemoryStream();
byte[] buffer = Convert.FromBase64String(text);
using (MemoryStream ms = new MemoryStream(buffer))
{
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
{
ds.CopyTo(resultStream);
ds.Close();
}
}
byte[] decompressedByte = resultStream.ToArray();
resultStream.Dispose();
return Encoding.Unicode.GetString(decompressedByte);
}
/// <summary>
/// 암호화
/// </summary>
/// <param name="encrypt"></param>
/// <returns></returns>
public string Encrypto(string encrypt)
{
//통신 암호화
#region To Base64
byte[] b = Encoding.UTF8.GetBytes(encrypt);
encrypt = Convert.ToBase64String(b);
#endregion
#region
Random rand = new Random();
encrypt = encrypt.Insert(0, str[rand.Next(str.Length)].ToString());
#endregion
#region
int l1 = (int)(encrypt.Length * 0.3f);
int l2 = l1 * 2;
int l3 = l1 * 3;
string s1 = encrypt.Substring(0, l1);
string s2 = encrypt.Substring(l1, l1);
string s3 = encrypt.Substring(l2, l1);
string s4 = encrypt.Substring(l3, encrypt.Length - l3);
encrypt = s4 + s2 + s3 + s1;
#endregion
encrypt = Encrypt(encrypt);
return encrypt;
}
/// <summary>
/// 복호화
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public string Decrypto(string cipherText)
{
string decrypt = cipherText;
decrypt = Decrypt(decrypt);
#region
int length = decrypt.Length;
int l1 = (int)(length * 0.3f);
int remainder = length - l1 * 3;
string s4 = decrypt.Substring(0, remainder);
string tmpds = decrypt.Substring(remainder);
string s3 = tmpds.Substring(0, l1);
string s2 = tmpds.Substring(l1, l1);
string s1 = tmpds.Substring(l1 * 2, l1);
decrypt = s1 + s3 + s2 + s4;
#endregion
#region
decrypt = decrypt.Substring(1);
#endregion
#region To Base64
byte[] b = Convert.FromBase64String(decrypt);
decrypt = Encoding.UTF8.GetString(b);
#endregion
return decrypt;
}
private const string strPassword = "sldkfghqpwo!)($%+sr=g234";
private const string vi = "f9v#d9OV*1Unf*%v";
// This constant is used to determine the keysize of the encryption algorithm.
private const int keysize = 256;
/// <summary>
/// 암호화
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public string Encrypt(string plainText)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(vi);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(strPassword, null);
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();
return Convert.ToBase64String(cipherTextBytes);
}
/// <summary>
/// 복호화
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public string Decrypt(string cipherText)
{
try
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(vi);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(strPassword, null);
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();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
catch
{
return string.Empty;
}
}
#region HTML
public static string RegularExpressionEncryption(string text)
{
return text.Replace("\\\"", "\"").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("\'", "&#39;").Replace("´", "&acute;").Replace("[", "&#91;").Replace("\\", "&#backslash;").Replace("]", "&#93;").Replace("{", "&#123;").Replace("}", "&#125;").Replace("\n", "&#linebreak;");
}
public static string RegularExpressionDecryption(string text)
{
return text.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace("&#39;", "\'").Replace("&acute;", "´").Replace("&#91;", "[").Replace("&#backslash;", "\\").Replace("&#93;", "]").Replace("&#123;", "{").Replace("&#125;", "}").Replace("&#linebreak;", "\n");
}
#endregion
#region
public string DecryptSchema(string textToDecrypt)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
byte[] pwdBytes = Encoding.UTF8.GetBytes(vi);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
public string EncryptSchema(string textToEncrypt)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = Encoding.UTF8.GetBytes(vi);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
}
#endregion
#region SHA256
SHA256 sha = new SHA256Managed();
public string SHA256Hash(string data)
{
byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data));
StringBuilder stringBuilder = new StringBuilder();
foreach (byte b in hash)
{
stringBuilder.AppendFormat("{0:x2}", b);
}
return stringBuilder.ToString();
}
#endregion
}

View File

@ -1,7 +1,10 @@
public enum Protocol public enum Protocol
{ {
//0~100 테스트용 프로토콜
Test = 0, Test = 0,
AddUser = 1, AddUser = 1,
//로그인,버전확인등등
Downlode = 100,
} }
public enum Error public enum Error

View File

@ -10,6 +10,7 @@ namespace Server.System
public static Thread thread; public static Thread thread;
private static AbstractGit git; private static AbstractGit git;
public static ErrorResp successResp;
public static string Process(HttpContext context) public static string Process(HttpContext context)
{ {
@ -18,16 +19,17 @@ namespace Server.System
try try
{ {
string eaDelivery = context.Request.Headers["X-Gitea-Delivery"]; string eaDelivery = context.Request.Headers["X-Gitea-Delivery"];
string eaEvent = context.Request.Headers["X-Gitea-Event"];
string eaEventType = context.Request.Headers["X-Gitea-Event-Type"];
string eaSignature = context.Request.Headers["X-Gitea-Signature"];
Console.WriteLine($"X-Gitea-Delivery : {eaDelivery}"); logger.Info($"SaveVersion : {eaDelivery}");
Console.WriteLine($"X-Gitea-Event : {eaEvent}");
Console.WriteLine($"X-Gitea-Event-Type : {eaEventType}");
Console.WriteLine($"X-Gitea-Signature : {eaSignature}");
//task를 쓰면 멈출수가 없기에 thread를 사용 //task를 쓰면 멈출수가 없기에 thread를 사용
Response = successResp.ToJson();
//무작위 공격을 대비한 1차적인 방어조치
if (eaDelivery == "" || eaDelivery.Length < 30)
return Response;
ProtocolProcessor.version = eaDelivery;
if (thread.ThreadState == ThreadState.Unstarted) if (thread.ThreadState == ThreadState.Unstarted)
{ {
thread.Start(); thread.Start();
@ -41,12 +43,6 @@ namespace Server.System
{ {
git.isRestart = true; git.isRestart = true;
} }
ErrorResp error = new ErrorResp();
error.status = 200;
error.message = "Success";
Response = error.ToJson();
} }
catch (RuntimeException ex) catch (RuntimeException ex)
{ {
@ -68,6 +64,8 @@ namespace Server.System
{ {
git = new XlsxToJson(); git = new XlsxToJson();
thread = new Thread(git.Init); thread = new Thread(git.Init);
successResp.status = 200;
successResp.message = "Success";
} }
} }
} }

View File

@ -4,8 +4,8 @@
{ {
#region Dev #region Dev
#if DEBUG #if DEBUG
public static readonly string SQL_URL = "Host=myHost;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase;"; public static readonly string SQL_URL = "Host=192.168.0.2;Port=5432;Username=manager;Password=Zn2zs558W5SdD8K;Database=project_thewar;";
public static readonly string EXCEL_SQL_URL = "Host=192.168.0.2;Port=5432;Username=manager;Password=BQNl01bJJF0wn9R;Database=project_thewar;"; public static readonly string EXCEL_SQL_URL = "Host=192.168.0.2;Port=5432;Username=manager;Password=Zn2zs558W5SdD8K;Database=project_thewar;";
#endif #endif
#endregion #endregion

View File

@ -7,6 +7,8 @@ namespace Server.System {
private static readonly NLog.ILogger logger = LogManager.GetCurrentClassLogger(); private static readonly NLog.ILogger logger = LogManager.GetCurrentClassLogger();
public static string cryptoData = "";
public static string version = "";
public static void addProtocol(AbstractService abstractService) { public static void addProtocol(AbstractService abstractService) {
if (SERVICE_DIC.ContainsKey(abstractService.ProtocolValue())) { if (SERVICE_DIC.ContainsKey(abstractService.ProtocolValue())) {

View File

@ -1 +1 @@
e06c50d31a8c60a25c1a22bc641412d14691fe3a 582bbf99862fd7ffd71f5c01bdc1aa70ee68d845

Binary file not shown.

View File

@ -133,3 +133,6 @@
2.0 2.0
2.0 2.0
2.0 2.0
2.0
2.0
2.0