public  string Encrypt(string str)
        {
            string result = null;
            if (str == null)
            {
                return result;
            }
            try
            {
                byte[] array0 = Encoding.ASCII.GetBytes(str);
                MemoryStream stream = new MemoryStream(array0);
                RijndaelManaged rijndaelManaged = new RijndaelManaged();
                byte[] key = new byte[32] { 5, 1, 3, 28, 27, 3, 2, 16, 12, 19, 39, 200, 10, 18, 181, 79, 103, 61, 145, 215, 125, 212, 131, 241, 229, 254, 250, 205, 11, 29, 83, 125 };
                byte[] vi = new byte[16] { 204, 19, 18, 10, 147, 108, 20, 177, 26, 171, 19, 143, 38, 112, 19, 12 };

                ICryptoTransform transform = rijndaelManaged.CreateEncryptor(key, vi);
                CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write);
                result = cryptoStream.ToString();
                cryptoStream.FlushFinalBlock();
                return result;
            }
            catch
            {
                return null;
            }
        }

        public  string Decode(string str)
        {
            string result = null;
            if (str == null)
            {
                return result;
            }

            try
            {
                byte[] array0 = Encoding.ASCII.GetBytes(str);
                MemoryStream stream = new MemoryStream(array0);
                RijndaelManaged rijndaelManaged = new RijndaelManaged();
                byte[] key = new byte[32] { 5, 1, 3, 28, 27, 3, 2, 16, 12, 19, 39, 200, 10, 18, 181, 79, 103, 61, 145, 215, 125, 212, 131, 241, 229, 254, 250, 205, 11, 29, 83, 125 };
                byte[] vi = new byte[16] { 204, 19, 18, 10, 147, 108, 20, 177, 26, 171, 19, 143, 38, 112, 19, 12 };

                ICryptoTransform transform = rijndaelManaged.CreateEncryptor(key, vi);
                CryptoStream inStream = new CryptoStream(stream, transform, CryptoStreamMode.Read);
                return inStream.ToString();
            }
            catch
            {
                return null;
            }
        }

1.代码中key和vi分别对应加密器对象Key和初始化向量 (IV)

2.Key和VI只有完全匹配得上加密数据才可以被解密

posted on 2019-06-20 13:36  Khandasas  阅读(658)  评论(0编辑  收藏  举报