ETC
C# 암호화 Encrypt / Decrypt ( Aes 128, Salt 추가, 파일 Master key 8 Byte 삽입)
NicSub
2021. 3. 18. 11:44
728x90
반응형
C# 암호화 / 복호화 Aes 128, Salt 추가, 파일 Master key 8 Byte 삽입)
Aes 암호화된 파일앞에 userid Unicode로 삽입
복호화에서 파일앞 8바이트 userid를 확인하고
나머지는 MemoryStream에 저장 > 복호화 진행(비밀번호 Salt확인)
point MemroyStream의 position이 마지막으로 가있으니 position을 처음으로 옮겨준다.
Mstream.Position = 0;
public static async Task EncryptFile(string inputFile, string outputFile)
{
try
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key =UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create );
RijndaelManaged RMCrypto = new RijndaelManaged();
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
string userid = "TestTest";
byte[] key2 = Encoding.UTF8.GetBytes(userid);
fsCrypt.Write(key2, 0, key2.Length);
CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
while ((data = fsIn.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
cs.FlushFinalBlock();
fsIn.Close();
cs.Close();
fsCrypt.Close();
return true;
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
return false;
}
}
public static async Task<bool> DecryptFile(string inputFile, string outputFile)
{
try
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fileStream = new FileStream(inputFile, FileMode.Open);
byte[] All_Byte = new byte[fileStream.Length];
using (MemoryStream Mstream = new MemoryStream())
{
string userid = "TestTest";
byte[] key2 = Encoding.UTF8.GetBytes(userid);
byte[] Data_first = new byte[key2.Length];
for (int i = 0; i < key2.Length; i++)
{
Data_first[i] = (byte)fileStream.ReadByte();
}
int data;
while ((data = fileStream.ReadByte()) != -1)
{
Mstream.WriteByte((byte)data);
}
RijndaelManaged RMCrypto = new RijndaelManaged();
Mstream.Position = 0;
CryptoStream cs = new CryptoStream(Mstream, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
Console.WriteLine(RMCrypto.Padding.ToString());
int dataB;
while ((dataB = cs.ReadByte()) != -1)
{
fsOut.WriteByte((byte)(dataB));
}
fsOut.Close();
cs.Close();
fileStream.Close();
return true;
} // using
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
return false;
}
}
반응형