C# AES-CTR模式 纯代码实现

本文介绍了如何将JavaScript中的AES-CTR加密算法移植到.NET中,包括SBox矩阵填充、轮密钥扩展、Counter模式加密与解密的详细步骤,适用于128/192/256位密钥的AES加密。
摘要由CSDN通过智能技术生成

工作需要移植了Javascript的AES-CTR的算法

using System.Text;

namespace SmartGate
{
    class AES
    {
        public static byte[,] Rcon = new byte[11, 4] {
                                {0x00, 0x00, 0x00, 0x00},
                                   {0x01, 0x00, 0x00, 0x00},
                                   {0x02, 0x00, 0x00, 0x00},
                                   {0x04, 0x00, 0x00, 0x00},
                                   {0x08, 0x00, 0x00, 0x00},
                                   {0x10, 0x00, 0x00, 0x00},
                                   {0x20, 0x00, 0x00, 0x00},
                                   {0x40, 0x00, 0x00, 0x00},
                                   {0x80, 0x00, 0x00, 0x00},
                                   {0x1b, 0x00, 0x00, 0x00},
                                   {0x36, 0x00, 0x00, 0x00} };
        public static byte[] Sbox = new byte[256] {  // populate the Sbox matrix
    /* 0     1     2     3     4     5     6     7     8     9     a     b     c     d     e     f */
    /*0*/  0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
    /*1*/  0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
    /*2*/  0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
    /*3*/  0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
    /*4*/  0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
    /*5*/  0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
    /*6*/  0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
    /*7*/  0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
    /*8*/  0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
    /*9*/  0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
    /*a*/  0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
    /*b*/  0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
    /*c*/  0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
    /*d*/  0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
    /*e*/  0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
    /*f*/  0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };

        private static byte[] RotWord(byte[] word)
        {
            byte[] result = new byte[4];
            result[0] = word[1];
            result[1] = word[2];
            result[2] = word[3];
            result[3] = word[0];
            return result;
        }
        private static byte[] SubWord(byte[] word)
        {
            byte[] result = new byte[4];
            result[0] = Sbox[(word[0] >> 4) * 16 + (word[0] & 0x0f)];
            result[1] = Sbox[(word[1] >> 4) * 16 + (word[1] & 0x0f)];
            result[2] = Sbox[(word[2] >> 4) * 16 + (word[2] & 0x0f)];
            result[3] = Sbox[(word[3] >> 4) * 16 + (word[3] & 0x0f)];
            return result;
        }

        private static byte[,] KeyExpansion(byte[] key)
        {
            var Nb = 4;               // block size (in words): no of columns in state (fixed at 4 for AES)
            var Nk = key.Length / 4;  // key length (in words): 4/6/8 for 128/192/256-bit keys
            var Nr = Nk + 6;          // no of rounds: 10/12/14 for 128/192/256-bit keys

            byte[,] w = new byte[Nb * (Nr + 1), 4];
            var temp = new byte[4];

            for (var i = 0; i < Nk; i++)
            {
                w[i, 0] = key[4 * i];
                w[i, 1] = key[4 * i + 1];
                w[i, 2] = key[4 * i + 2];
                w[i, 3] = key[4 * i + 3];
            }

            for (var i = Nk; i < (Nb * (Nr + 1)); i++)
            {
                for (int t = 0; t < 4; t++)
                {
                    temp[t] = w[i - 1, t];
                };
                if (i % Nk == 0)
                {
                    temp = SubWord(RotWord(temp));
                    for (var t = 0; t < 4; t++)
                    {
                        temp[t] ^= Rcon[i / Nk, t];
                    };
                }
                else if (Nk > 6 && i % Nk == 4)
                {
                    temp = SubWord(temp);
                }
                for (int t = 0; t < 4; t++)
                {
                    w[i, t] = (byte)(w[i - Nk, t] ^ temp[t]);
                };
            }
            return w;
        }

        /** 
         * Encrypt a text using AES encryption in Counter mode of operation
         *
         * Unicode multi-byte character safe
         *
         * @param {String} plaintext Source text to be encrypted
         * @param {String} password  The password to use to generate a key
         * @param {Number} nBits     Number of bits to be used in the key (128, 192, or 256)
         * @returns {string}         Encrypted text
         */
        public static string Encrypt(string plainText, string password, int nBits)
        {
            int blockSize = 16;
            if (!(nBits == 128 || nBits == 192 || nBits == 256))
            {
                return "";
            }
            int nBytes = nBits / 8;
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);//convert type string to byte[]
            byte[] _pwBytes = Encoding.UTF8.GetBytes(password);
            byte[] pwBytes = new byte[nBytes];
            Array.Copy(_pwBytes, 0, pwBytes, 0, _pwBytes.Length);//fill password to 128bit
            byte[] key = Cipher(pwBytes, KeyExpansion(pwBytes));
            if (nBytes != 16)
            {
                byte[] slice = new byte[nBytes - 16];
                Array.Copy(key, 0, slice, 0, nBytes - 16);
                byte[] _key = new byte[nBytes];
                Array.Copy(key, 0, _key, 0, 16);
                Array.Copy(slice, 16, _key, 0, nBytes - 16);
                key = _key;
            }

            byte[] counterBlock = new byte[blockSize];
            //long nonce = DateTime.Now.Millisecond;
            long nonce = 1648711406264;
            long nonceSec = nonce / 1000;
            long nonceMs = nonce % 1000;

            for (var i = 0; i < 4; i++)
            {
                counterBlock[i] = (byte)((nonceSec >> i * 8) & 0xff);
            }
            for (var i = 0; i < 4; i++)
            {
                counterBlock[i + 4] = (byte)(nonceMs & 0xff);
            }
            // and convert it to a string to go on the front of the ciphertext
            List<byte> cipherList = new List<byte>();

            byte[] _ctrTxt = new byte[8];
            Array.Copy(counterBlock, 0, _ctrTxt, 0, 8);
            cipherList.AddRange(_ctrTxt);
            var keySchedule = KeyExpansion(key);
            int blockCount = (int)Math.Ceiling((double)plainTextBytes.Length / blockSize);
            for (var b = 0; b < blockCount; b++)
            {
                // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
                // done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
                for (var c = 0; c < 4; c++)
                {
                    counterBlock[15 - c] = (byte)((b >> c * 8) & 0xff);
                }
                for (var c = 0; c < 4; c++)
                {
                    counterBlock[15 - c - 4] = ((byte)(b / 0x100000000 >> c * 8));
                }

                var cipherCntr = Cipher(counterBlock, keySchedule);  // -- encrypt counter block --

                // block size is reduced on final block
                int blockLength = b < blockCount - 1 ? blockSize : (plainTextBytes.Length - 1) % blockSize + 1;
                byte[] cipherChar = new byte[blockLength];

                for (var i = 0; i < blockLength; i++)
                {  // -- xor plaintext with ciphered counter char-by-char --
                    cipherChar[i] = (byte)(cipherCntr[i] ^ plainTextBytes[b * blockSize + i]);
                }
                cipherList.AddRange(cipherChar);
            }
            string ciphertxt = Convert.ToBase64String(cipherList.ToArray());
            return ciphertxt;
        }
        private static byte[] Cipher(byte[] input, byte[,] w)
        {
            var Nb = 4;               // block size (in words): no of columns in state (fixed at 4 for AES)
            var Nr = w.GetLength(0) / Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys

            byte[,] state = new byte[4, Nb];  // initialise 4xNb byte-array 'state' with input [§3.4]
            for (int i = 0; i < 4 * Nb; i++)
            {
                state[i % 4, i / 4] = input[i];
            };

            state = AddRoundKey(state, w, 0, Nb);

            for (var round = 1; round < Nr; round++)
            {
                state = SubBytes(state, Nb);
                state = ShiftRows(state, Nb);
                state = MixColumns(state, Nb);
                state = AddRoundKey(state, w, round, Nb);
            }

            state = SubBytes(state, Nb);
            state = ShiftRows(state, Nb);
            state = AddRoundKey(state, w, Nr, Nb);

            byte[] output = new byte[4 * Nb];  // convert state to 1-d array before returning [§3.4]
            for (var i = 0; i < 4 * Nb; i++)
            {
                output[i] = state[i % 4, i / 4];
            }
            return output;
        }

        private static byte[,] MixColumns(byte[,] s, int Nb)
        {
            for (var c = 0; c < 4; c++)
            {
                byte[] a = new byte[4];  // 'a' is a copy of the current column from 's'
                byte[] b = new byte[4];  // 'b' is a•{02} in GF(2^8)
                for (var i = 0; i < 4; i++)
                {
                    a[i] = s[i, c];
                    b[i] = (byte)((s[i, c] & 0x80) != 0 ? s[i, c] << 1 ^ 0x011b : s[i, c] << 1);
                }
                // a[n] ^ b[n] is a•{03} in GF(2^8)
                s[0, c] = (byte)(b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]); // 2*a0 + 3*a1 + a2 + a3
                s[1, c] = (byte)(a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]); // a0 * 2*a1 + 3*a2 + a3
                s[2, c] = (byte)(a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]); // a0 + a1 + 2*a2 + 3*a3
                s[3, c] = (byte)(a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]); // 3*a0 + a1 + a2 + 2*a3
            }
            return s;
        }

        private static byte[,] ShiftRows(byte[,] s, int Nb)
        {
            byte[] t = new byte[4];
            for (var r = 1; r < 4; r++)
            {
                for (var c = 0; c < 4; c++)
                {
                    t[c] = s[r, (c + r) % Nb];
                };  // shift into temp copy
                for (var c = 0; c < 4; c++)
                {
                    s[r, c] = t[c];
                };         // and copy back
            }          // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
            return s;  // see asmaes.sourceforge.net/rijndael/rijndaelImplementation.pdf
        }

        private static byte[,] SubBytes(byte[,] s, int Nb)
        {
            for (var r = 0; r < 4; r++)
            {
                for (var c = 0; c < Nb; c++)
                {
                    s[r, c] = Sbox[s[r, c]];
                };
            }
            return s;
        }

        private static byte[,] AddRoundKey(byte[,] state, byte[,] w, int rnd, int Nb)
        {
            for (var r = 0; r < 4; r++)
            {
                for (var c = 0; c < Nb; c++) state[r, c] ^= w[rnd * 4 + c, r];
            }
            return state;

        }

        /** 
         * Decrypt a text encrypted by AES in counter mode of operation
         *
         * @param {String} ciphertext Source text to be encrypted
         * @param {String} password   The password to use to generate a key
         * @param {Number} nBits      Number of bits to be used in the key (128, 192, or 256)
         * @returns {String}          Decrypted text
         */
        public static string Decrypt(string cipherText, string password, int nBits)
        {
            int blockSize = 16;  // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
            if (!(nBits == 128 || nBits == 192 || nBits == 256))
            {
                return "";
            }// standard allows 128/192/256 bit keys
            byte[] cipherByte = Convert.FromBase64String(cipherText);

            // use AES to encrypt password (mirroring encrypt routine)
            int nBytes = nBits / 8;
            byte[] _pwBytes = Encoding.UTF8.GetBytes(password);
            byte[] pwBytes = new byte[nBytes];
            Array.Copy(_pwBytes, 0, pwBytes, 0, _pwBytes.Length);
            byte[] key = Cipher(pwBytes, KeyExpansion(pwBytes));

            if (nBytes != 16)
            {
                byte[] slice = new byte[nBytes - 16];
                Array.Copy(key, 0, slice, 0, nBytes - 16);
                byte[] _key = new byte[nBytes];
                Array.Copy(key, 0, _key, 0, 16);
                Array.Copy(slice, 16, _key, 0, nBytes - 16);
                key = _key;
            }

            //alert("key:"+key);
            // recover nonce from 1st 8 bytes of ciphertext
            byte[] counterBlock = new byte[blockSize];
            Array.Copy(cipherByte, 0, counterBlock, 0, 8);

            // generate key schedule
            var keySchedule = KeyExpansion(key);

            // separate ciphertext into blocks (skipping past initial 8 bytes)
            int nBlocks = (int)Math.Ceiling((double)(cipherByte.Length - 8) / blockSize);
            List<byte[]> cipherTextList = new List<byte[]>(nBlocks);
            for (var b = 0; b < nBlocks; b++)
            {
                int blockLenght = cipherByte.Length - 8 - b * blockSize > blockSize ? blockSize : cipherByte.Length - 8 - b * blockSize;
                byte[] cipherTextBlock = new byte[blockLenght];
                Array.Copy(cipherByte, 8 + b * blockSize, cipherTextBlock, 0, blockLenght);
                cipherTextList.Add(cipherTextBlock);
            }

            // plaintext will get generated block-by-block into array of block-length strings
            List<byte> plainTextArray = new List<byte>();
            for (var b = 0; b < nBlocks; b++)
            {
                // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
                for (var c = 0; c < 4; c++)
                {
                    counterBlock[15 - c] = (byte)((b >> c * 8) & 0xff); ;
                }
                for (var c = 0; c < 4; c++)
                {
                    counterBlock[15 - c - 4] = (byte)(b / 0x100000000 >> c * 8);
                }

                //alert("counterBlock:"+counterBlock);
                var cipherCntr = Cipher(counterBlock, keySchedule);  // encrypt counter block
                                                                     //alert("cipherCntr:"+cipherCntr);

                byte[] plaintxtByte = new byte[cipherTextList[b].Length];
                for (var i = 0; i < cipherTextList[b].Length; i++)
                {
                    // -- xor plaintxt with ciphered counter byte-by-byte --
                    plaintxtByte[i] = (byte)(cipherCntr[i] ^ cipherTextList[b][i]);
                }
                plainTextArray.AddRange(plaintxtByte);
            }

            // join array of blocks into single plaintext string
            byte[] plainTextByte = plainTextArray.ToArray();
            string plainText = Encoding.ASCII.GetString(plainTextByte);  // decode from UTF8 back to Unicode multi-byte chars

            return plainText;
        }
    }
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值