본문 바로가기

카테고리 없음

C# 암호화 복호화 샘플 Key Salt

반응형

sample.cs
0.00MB

해당 샘플을 이용하여 최초 암호생성시 new GUID등를 이용하여 key salt

저장하여 각 클라이언트마다 고유의 암복화 모듈을 갖게 된다.


using System;
using System.Security.Cryptography;
using System.Text;

public class AesEncryptionSample
{
    public static string Encrypt(string plainText, string key, string salt)
    {
        using (Aes aesAlg = Aes.Create())
        {
            Rfc2898DeriveBytes keyDerivation = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(salt), 10000);
            aesAlg.Key = keyDerivation.GetBytes(32); // 256-bit key
            aesAlg.IV = keyDerivation.GetBytes(16); // 128-bit IV

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
            byte[] encryptedBytes = null;

            using (var msEncrypt = new System.IO.MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encryptedBytes = msEncrypt.ToArray();
                }
            }
            return Convert.ToBase64String(encryptedBytes);
        }
    }

    public static string Decrypt(string encryptedText, string key, string salt)
    {
        using (Aes aesAlg = Aes.Create())
        {
            Rfc2898DeriveBytes keyDerivation = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(salt), 10000);
            aesAlg.Key = keyDerivation.GetBytes(32);
            aesAlg.IV = keyDerivation.GetBytes(16);

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            string decryptedText = null;

            using (var msDecrypt = new System.IO.MemoryStream(encryptedBytes))
            {
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
                    {
                        decryptedText = srDecrypt.ReadToEnd();
                    }
                }
            }
            return decryptedText;
        }
    }

    public static void Main()
    {
        string originalText = "Hello, world!";
        string key = "YourSecretKey";  
        string salt = "RandomSalt"; 

        string encryptedText = Encrypt(originalText, key, salt);
        Console.WriteLine("Encrypted: " + encryptedText);

        string decryptedText = Decrypt(encryptedText, key, salt);
        Console.WriteLine("Decrypted: " + decryptedText);
    }
}