private byte[] key; // 存储加密密钥 private byte[] iv; // 存储初始化向量 //加密方法 public string Encrypt(string text) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(text); // 将文本转换为字节数组 using (Aes aes = Aes.Create()) // 使用AES加密算法 { key = aes.Key; // 保存生成的密钥 iv = aes.IV; // 保存生成的初始化向量 using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv)) // 创建加密器 { byte[] encryptedBytes = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length); // 进行加密 byte[] combinedBytes = new byte[iv.Length + encryptedBytes.Length]; // 创建一个合并后的字节数组 Array.Copy(iv, 0, combinedBytes, 0, iv.Length); // 复制初始化向量到合并数组的开头 Array.Copy(encryptedBytes, 0, combinedBytes, iv.Length, encryptedBytes.Length); // 复制加密后的字节到合并数组 return Convert.ToBase64String(combinedBytes); // 返回Base64编码的加密字符串 } } } //解密方法 public int Decrypt(string encryptedText) { byte[] combinedBytes = Convert.FromBase64String(encryptedText); // 将Base64编码的加密字符串转换为字节数组 byte[] iv = new byte[16]; // 重新创建一个用于存储初始化向量的字节数组 byte[] encryptedBytes = new byte[combinedBytes.Length - iv.Length]; // 创建一个用于存储加密后的字节数组 Array.Copy(combinedBytes, 0, iv, 0, iv.Length); // 复制出初始化向量 Array.Copy(combinedBytes, iv.Length, encryptedBytes, 0, encryptedBytes.Length); // 复制出加密后的字节 using (Aes aes = Aes.Create()) // 使用AES加密算法 { aes.Key = key; // 设置解密密钥 aes.IV = iv; // 设置解密初始化向量 using (ICryptoTransform decryptor = aes.CreateDecryptor(key, iv)) // 创建解密器 { byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); // 进行解密 string decryptedText = Encoding.UTF8.GetString(decryptedBytes); // 将解密后的字节数组转换为字符串 return Convert.ToInt32(decryptedText); // 将解密后的字符串转换为整数并返回 } } }
C# AES加密算法,可以实现逆向解密成明文
最新推荐文章于 2024-10-11 14:25:11 发布