[c#] 직렬화와 암호화
소프트웨어 개발에서 데이터 보안은 매우 중요한 측면입니다. 데이터를 안전하게 저장하고 전송하기 위해 직렬화와 암호화 기술을 사용할 수 있습니다.
직렬화
직렬화는 개체를 바이트 스트림으로 변환하는 과정을 말합니다. C#에서는 System.Runtime.Serialization
네임스페이스의 클래스를 사용하여 직렬화를 수행할 수 있습니다.
예를 들어, 다음과 같이 클래스를 직렬화할 수 있습니다:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
Person person = new Person { Name = "John", Age = 30 };
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, person);
byte[] data = stream.ToArray();
// 저장된 데이터 또는 데이터 전송
}
}
}
암호화
암호화는 평문 데이터를 암호키를 사용하여 암호화된 형태로 변환하는 과정을 말합니다. C#에서는 System.Security.Cryptography
네임스페이스의 클래스를 사용하여 암호화를 수행할 수 있습니다.
예를 들어, 다음과 같이 데이터를 암호화할 수 있습니다:
using System;
using System.Text;
using System.Security.Cryptography;
public class Program
{
public static void Main()
{
string plainText = "Sensitive data to be encrypted";
byte[] key = Encoding.UTF8.GetBytes("16ByteKeyForAES");
byte[] iv = Encoding.UTF8.GetBytes("16ByteInitialVec");
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] encryptedData = null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
encryptedData = ms.ToArray();
// 저장된 암호화된 데이터 또는 데이터 전송
}
}
}
}
}
직렬화와 암호화를 함께 사용하여 데이터를 안전하게 저장하고 전송할 수 있습니다.
참고 문헌:
- https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/
- https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography?view=net-5.0