加密和解密算法

   /// <summary>
    /// 获取密钥
    /// </summary>
    private static string _key1
    {
        get
        {
            return "abcdef1234567890";    ////必须是16位
        }
    }
    private static byte[] _vi = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 
    /// <summary>AES加密</summary>  
    /// <param name="key">密钥,长度为16的字符串</param>  
    /// <param name="iv">偏移量,长度为16的字符串</param>  
    /// <returns>密文</returns>  
    public static string EncodeAES(string text, string iv)
    {
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        rijndaelCipher.Mode = CipherMode.CBC;
        rijndaelCipher.Padding = PaddingMode.Zeros;
        rijndaelCipher.KeySize = 128;
        rijndaelCipher.BlockSize = 128;
        byte[] pwdBytes =Encoding.UTF8.GetBytes(_key1);
        byte[] keyBytes = new byte[16];
        int len = pwdBytes.Length;
        if (len > keyBytes.Length)
            len = keyBytes.Length;
        System.Array.Copy(pwdBytes, keyBytes, len);
        rijndaelCipher.Key = keyBytes;
        rijndaelCipher.IV = _vi;
        ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
        byte[] plainText = Encoding.UTF8.GetBytes(text);
        byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
        return Convert.ToBase64String(cipherBytes);
    }

    /// <summary>AES解密</summary>  
    /// <param name="text">密文</param>  
    /// <param name="key">密钥,长度为16的字符串</param>  
    /// <param name="iv">偏移量,长度为16的字符串</param>  
    /// <returns>明文</returns>  
    public static string DecodeAES(string text)
    {
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        rijndaelCipher.Mode = CipherMode.CBC;
        rijndaelCipher.Padding = PaddingMode.Zeros;
        rijndaelCipher.KeySize = 128;
        rijndaelCipher.BlockSize = 128;
        byte[] encryptedData = Convert.FromBase64String(text);
        byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(_key1);
        byte[] keyBytes = new byte[16];
        int len = pwdBytes.Length;
        if (len > keyBytes.Length)
            len = keyBytes.Length;
        System.Array.Copy(pwdBytes, keyBytes, len);
        rijndaelCipher.Key = keyBytes;
        rijndaelCipher.IV = _vi;
        ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
        byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
        return Encoding.UTF8.GetString(plainText);
    }  

  

posted on 2014-08-08 10:35  记性特差  阅读(328)  评论(0)    收藏  举报