프로젝트

일반

사용자정보

AES-256 암호화 소스

송 경석이(가) 2달 전에 추가함

using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;

class AesBouncyCastle
{
    private static readonly Encoding Encoding = Encoding.UTF8;

    public static byte[] Encrypt(string plainText, byte[] key, byte[] iv)
    {
        return ProcessCipher(true, Encoding.GetBytes(plainText), key, iv);
    }

    public static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
    {
        byte[] decryptedBytes = ProcessCipher(false, cipherText, key, iv);
        return Encoding.GetString(decryptedBytes);
    }

    private static byte[] ProcessCipher(bool forEncryption, byte[] input, byte[] key, byte[] iv)
    {
        IBufferedCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));
        KeyParameter keyParam = new KeyParameter(key);
        ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv);

        cipher.Init(forEncryption, keyParamWithIV);

        byte[] output = new byte[cipher.GetOutputSize(input.Length)];
        int length = cipher.ProcessBytes(input, 0, input.Length, output, 0);
        length += cipher.DoFinal(output, length);

        Array.Resize(ref output, length);
        return output;
    }

    public static void Main()
    {
        string plainText = "Hello, BouncyCastle AES-256!";
        byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef0123456789abcdef"); // 32 bytes key
        byte[] iv = Encoding.UTF8.GetBytes("abcdef9876543210"); // 16 bytes IV

        byte[] encrypted = Encrypt(plainText, key, iv);
        Console.WriteLine($"Encrypted: {Convert.ToBase64String(encrypted)}");

        string decrypted = Decrypt(encrypted, key, iv);
        Console.WriteLine($"Decrypted: {decrypted}");
    }
}