【Unity】AES(Rijndael)による暗号化と復号化

最終更新日

古い.net subset 2.0 環境下で、AES(Rijndael)による暗号化と復号化を行うサンプルコードになります。

確認バージョン

Unity5.3.4p2

ソースコード

using UnityEngine;
using System;
using System.Collections;
using System.Security.Cryptography;
using System.IO;
using System.Text;

public static partial class AES
{
    const int BLOCK_SIZE = 16;

    static private RijndaelManaged CreateRijndaelManaged( byte[] _key, byte[] _iv )
    {
        RijndaelManaged aes = new RijndaelManaged();
        aes.BlockSize = BLOCK_SIZE * 8;
        aes.KeySize = _key.Length * 8;
        aes.Mode = CipherMode.CFB;
        aes.FeedbackSize = 128;
        aes.Padding = PaddingMode.None;
        aes.Key = _key;
        aes.IV = _iv;
        return aes;
    }

    // 暗号化します。
    static public byte[] Encrypt( byte[] _plainText, byte[] _key, byte[] _iv )
    {
        // 16byteアライメントしたバッファを確保。
        int remainder = _plainText.Length % BLOCK_SIZE;
        byte[] worktext = new byte[_plainText.Length + (BLOCK_SIZE * (remainder != 0 ? 1 : 0) - remainder)];
        _plainText.CopyTo(worktext, 0);

        using(RijndaelManaged Aes = CreateRijndaelManaged(_key, _iv))
        {
            using(ICryptoTransform encryptor = Aes.CreateEncryptor())
            {
                using(MemoryStream msEncrypt = new MemoryStream())
                {
                    using(CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        BinaryWriter bw = new BinaryWriter(csEncrypt, Encoding.UTF8);
                        bw.Write(worktext);
                        bw.Close();
                        byte[] cipherText = msEncrypt.ToArray();
                        return cipherText;
                    }
                }
            }
        }
    }

    // 復号化します。
    static public byte[] Decrypt( byte[] _cipherText, byte[] _key, byte[] _iv )
    {   
        int remainder = _cipherText.Length % BLOCK_SIZE;
        byte[] worktext = new byte[_cipherText.Length + (BLOCK_SIZE * (remainder != 0 ? 1 : 0) - remainder)];
        _cipherText.CopyTo(worktext, 0);

        using (RijndaelManaged Aes = CreateRijndaelManaged(_key, _iv))
        {
            using (ICryptoTransform decryptor = Aes.CreateDecryptor())
            {
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Write))
                    {
                        BinaryWriter bw = new BinaryWriter(csEncrypt, Encoding.UTF8);
                        bw.Write(worktext);
                        bw.Close();
                        byte[] plainText = msEncrypt.ToArray();
                        return plainText;
                    }
                }
            }
        }
    }
}

鍵がばれると一撃ですが、生データよりはマシだと思います。

シェアする