https://www.youtube.com/watch?v=mlzxpkdXP58
using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public class AES : MonoBehaviour
{
public string EncryptAES(string textToEncrypt, string key)
{
RijndaelManaged rijndaelCipher = GetRijndaelCipher(key);
byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
return Convert.ToBase64String(rijndaelCipher.CreateEncryptor().TransformFinalBlock(plainText, 0, plainText.Length));
}
public string DecryptAES(string textToDecrypt, string key)
{
RijndaelManaged rijndaelCipher = GetRijndaelCipher(key);
byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
RijndaelManaged GetRijndaelCipher(string key)
{
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
Array.Copy(pwdBytes, keyBytes, len);
return new RijndaelManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
KeySize = 128,
BlockSize = 128,
Key = keyBytes,
IV = keyBytes
};
}
void Start()
{
string key = "encryp Key";
string original = "targetText";
string encrypted = EncryptAES(original, key);
string roundtrip = DecryptAES(encrypted, key);
print($"Encrypted: {encrypted}");
print($"Round Trip: {roundtrip}");
}
}
옛날에 만든거라 보안 수준 낮음
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class CryptManager : MonoBehaviour
{
const string privateKey = "12312rsefs09f8asflkawjfa0w98u";
public static string Encrypt(string data)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
RijndaelManaged rm = CreateRijndaelManaged();
ICryptoTransform ct = rm.CreateEncryptor();
byte[] results = ct.TransformFinalBlock(bytes, 0, bytes.Length);
return System.Convert.ToBase64String(results, 0, results.Length);
}
public static string Decrypt(string data)
{
byte[] bytes = System.Convert.FromBase64String(data);
RijndaelManaged rm = CreateRijndaelManaged();
ICryptoTransform ct = rm.CreateDecryptor();
byte[] resultArray = ct.TransformFinalBlock(bytes, 0, bytes.Length);
return System.Text.Encoding.UTF8.GetString(resultArray);
}
private static RijndaelManaged CreateRijndaelManaged()
{
byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(privateKey);
RijndaelManaged result = new RijndaelManaged();
byte[] newKeysArray = new byte[16];
System.Array.Copy(keyArray, 0, newKeysArray, 0, 16);
result.Key = newKeysArray;
result.Mode = CipherMode.ECB;
result.Padding = PaddingMode.PKCS7;
return result;
}
}
AesGcm
난수 1회성 보안키 방식
using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public class AesGcmSession : MonoBehaviour
{
const int KeySize = 32; // 256‑bit
const int NonceSize = 12; // 96‑bit (GCM 권장)
const int TagSize = 16; // 128‑bit auth tag
byte[] sessionKey; // 실행마다 새로 생성
// ───────────────────────────── 초기화 ─────────────────────────────
void Awake()
{
// 1) 세션 키 생성
sessionKey = RandomNumberGenerator.GetBytes(KeySize);
// 2) (예시) 콘솔로 보내고, 실제 서비스에선 안전 채널(HTTPS, WebSocket TLS 등)로
Debug.Log($"[Key to share] {Convert.ToBase64String(sessionKey)}");
}
// ─────────────────────────── 암호화 함수 ──────────────────────────
public string Encrypt(string plaintext, ulong nonceCounter /*ex: 증가형*/)
{
// 1) Nonce = 8바이트 카운터 + 4바이트 난수 (충돌 방지 & 추적 용이)
byte[] nonce = new byte[NonceSize];
BitConverter.GetBytes(nonceCounter).CopyTo(nonce, 0); // little‑endian
RandomNumberGenerator.GetBytes(nonce.AsSpan(8, 4)); // 하위 4바이트 무작위
byte[] plainBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] cipherBytes = new byte[plainBytes.Length];
byte[] tag = new byte[TagSize];
using var aes = new AesGcm(sessionKey);
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
// nonce‖tag‖ciphertext 순으로 묶어 베이스64
byte[] packet = new byte[NonceSize + TagSize + cipherBytes.Length];
Buffer.BlockCopy(nonce, 0, packet, 0, NonceSize);
Buffer.BlockCopy(tag, 0, packet, NonceSize, TagSize);
Buffer.BlockCopy(cipherBytes, 0, packet, NonceSize+TagSize, cipherBytes.Length);
return Convert.ToBase64String(packet);
}
// ─────────────────────────── 복호화 함수 ──────────────────────────
public string Decrypt(string base64Packet)
{
byte[] packet = Convert.FromBase64String(base64Packet);
byte[] nonce = packet[..NonceSize];
byte[] tag = packet[NonceSize..(NonceSize+TagSize)];
byte[] cipher = packet[(NonceSize+TagSize)..];
byte[] plainBytes = new byte[cipher.Length];
using var aes = new AesGcm(sessionKey);
aes.Decrypt(nonce, cipher, tag, plainBytes);
return Encoding.UTF8.GetString(plainBytes);
}
// ───────────────────────────── demo ─────────────────────────────
void Start()
{
string msg = "Hello, GCM!";
string enc = Encrypt(msg, 1); // nonceCounter 증가하며 사용
string dec = Decrypt(enc);
Debug.Log($"Encrypted (b64): {enc}");
Debug.Log($"Decrypted: {dec}");
}
}