AES(Rijndael)による暗号化と復号化
AES(Rijndael)による暗号化と復号化を行うサンプルコードです。Unityとかでも使えるかと思います。
ソースコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
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 ) { // _cipherTextを16byteアライメントしたバッファにコピー。 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; } } } } } } |
渡すキーの長さは32byteで確認しています。