C# AES 加解密示範

AES 在加解密的時候會需要用到 Key (金鑰) 和 IV (偏移量),
    
    public static void Main()
    {
        string original = "Here is some data to encrypt!";
        Console.WriteLine($"original: {original}");


        // 產生隨機金鑰
        using Aes myAes = Aes.Create();
        byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
        Console.WriteLine($"encrypted: {Convert.ToBase64String(encrypted)}");

        string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
        Console.WriteLine($"roundtrip: {roundtrip}");
    }

    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText 不能為空");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("key 不能為空");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("iv 不能為空");
        byte[] encrypted;

        using Aes aesAlg = Aes.Create();
        aesAlg.Key = Key;
        aesAlg.IV = IV;

        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                using (var streamWriter = new StreamWriter(cryptoStream))
                {
                    streamWriter.Write(plainText);
                }

                encrypted = memoryStream.ToArray();
            }
        }

        return encrypted;
    }

    static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] key, byte[] iv)
    {
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText 不能為空");
        if (key == null || key.Length <= 0)
            throw new ArgumentNullException("key 不能為空");
        if (iv == null || iv.Length <= 0)
            throw new ArgumentNullException("iv 不能為空");

        string plaintext = string.Empty;

        using Aes aesAlg = Aes.Create();
        aesAlg.Key = key;
        aesAlg.IV = iv;

        ICryptoTransform cryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

        using (MemoryStream memoryStream = new MemoryStream(cipherText))
        {
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
            {
                using (StreamReader streamReader = new StreamReader(cryptoStream))
                {
                    plaintext = streamReader.ReadToEnd();
                }
            }
        }

        return plaintext;
    }
    

留言