[c#] C# 직렬화와 암호화
C#에서 개발하는 애플리케이션에서 데이터를 안전하게 저장하고 전송하기 위해 직렬화와 암호화 기술을 사용할 수 있습니다. 직렬화는 객체를 바이트 스트림으로 변환하여 저장하거나 전송할 수 있는 기술이며, 암호화는 데이터를 안전하게 보호하는 기술입니다.
직렬화(Serialization)
C#에서는 객체를 직렬화하여 파일에 저장하거나 네트워크를 통해 전송할 수 있습니다. 가장 일반적인 방법은 BinaryFormatter
, DataContractSerializer
, Json.NET
등을 사용하는 것입니다.
아래는 Json.NET
을 사용하여 간단한 객체를 직렬화하는 예제입니다.
using Newtonsoft.Json;
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 Doe", Age = 30 };
string json = JsonConvert.SerializeObject(person);
Console.WriteLine(json);
}
}
암호화(Encryption)
C#에서는 System.Security.Cryptography
네임스페이스를 사용하여 데이터를 암호화할 수 있습니다. 가장 일반적인 방법은 대칭키 알고리즘인 AES(AESManaged)나 비대칭키 알고리즘인 RSA(RSACryptoServiceProvider)을 사용하는 것입니다.
아래는 AES를 사용하여 문자열을 암호화하는 예제입니다.
using System;
using System.Security.Cryptography;
using System.Text;
public class AesExample
{
public static void Main()
{
string plainText = "Hello, World!";
using (Aes aes = Aes.Create())
{
byte[] encrypted = EncryptStringToBytes_Aes(plainText, aes.Key, aes.IV);
Console.WriteLine(Convert.ToBase64String(encrypted));
}
}
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
byte[] encrypted;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
}
직렬화와 암호화를 통해 C# 애플리케이션에서 안전하고 보안된 데이터를 다룰 수 있습니다.
참조
- Newtonsoft.Json: https://www.newtonsoft.com/json
- C# Programming Guide - Serialization: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/index
- C# Programming Guide - Cryptography: https://docs.microsoft.com/en-us/dotnet/standard/security/cryptography-model