在 C# 中使用 AES 加密

2023-12-04

我似乎找不到使用 AES 128 位加密的清晰示例。

有人有一些示例代码吗?


如果您只想使用内置加密提供程序 RijndaelManaged,请查看以下帮助文章(它还有一个简单的代码示例):

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanagement.aspx

如果您急需样本,这里是所有抄袭的荣耀:

using System;
using System.IO;
using System.Security.Cryptography;

namespace RijndaelManaged_Example
{
    class RijndaelExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the RijndaelManaged 
                // class.  This generates a new key and initialization  
                // vector (IV). 
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {

                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    // Encrypt the string to an array of bytes. 
                    byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                    // Decrypt the bytes to a string. 
                    string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption. 
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream. 
            return encrypted;

        }

        static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold 
            // the decrypted text. 
            string plaintext = null;

            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption. 
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream 
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中使用 AES 加密 的相关文章

随机推荐

  • 是否有内置包可以将 html 解析为 dom?

    I found HTMLParser对于 SAX 和xml minidom对于 XML 我有一个结构良好的 HTML 所以我不需要太强大的解析器 有什么建议吗 我会推荐lxml 我喜欢 BeautifulSoup 但通常存在维护问题以及与后
  • tf.assign 到变量切片在 tf.while_loop 中不起作用

    下面的代码有什么问题 这tf assign当应用于 a 的切片时 op 工作得很好tf Variable如果它发生在循环之外 但是 在这种情况下 它会给出以下错误 import tensorflow as tf v 1 1 0 0 0 0
  • 如何在 Spring Cloud Gateway .yml 配置中禁用全局 CORS 配置以允许来自任何来源的请求?

    我想为我的微服务应用程序创建一个网关服务 并添加 Spring Cloud Gateway 文档中提到的配置以在网关中禁用 CORS spring GATEWAY CONFIG cloud gateway globalcors corsCo
  • 如何将 python 对象 pickle 到 csv 文件中?

    我正在尝试将 python 对象 pickle 到 csv 文件中 我想将对象的 pickle 写入文件中的第三列 我想使用 pickle 来避免为复杂对象编写序列化 写入 csv 的代码 with open self file path
  • 从 PHP 执行 Ruby 脚本并获取输出

    我有这个 Ruby 脚本 test rb print hello 我有这个 PHP 脚本 test php cmd ruby test rb system cmd 现在我通过 CLI 调用 PHP 脚本 php test php 我没有得到
  • 替换标识结束字符的多行

    我有下面的代码 CREATE TABLE Table1 column1 double NOT NULL column2 varchar 60 NULL column3 varchar 60 NULL column4 double NOT N
  • Apache Commons 电子邮件使用 base64 进行编码附加

    我正在尝试通过以下方式发送 base64 编码的文件apache commons mail我似乎无法理解Content Transfer Encoding base64标头应该去的地方 Create the email MultiPartE
  • 使用另一个文件夹中的 git“log”

    我在目录中A 我该如何执行git log对于目录中的 git 存储库B From man git 您可以使用 git dir参数 在传递任何命令之前 git git dir foo bar git log 指定 git目录是必要的 从文档
  • 如何在不同时间向 facebook 请求不同的权限?

    Facebook 建议 在使用 Facebook 登录时 您应该首先向用户请求尽可能少的权限 特别是避免请求发布权限 直到用户需要通过您的网站发布某些内容 https developers facebook com docs faceboo
  • 用于在窗口上打印串行数据的Python代码。

    我对 python 和 pyserial 很陌生 我的电脑安装了带有 pyserial 的 python 2 7 4 我想在我的电脑上的单独窗口上打印串行接收的数据 首先必须打开窗口 然后在该窗口上打印串行数据 这里必须打开一次窗口 并且必
  • 什么会让 git 在 git pull --rebase 期间删除本地文件?

    我正在尝试重现我尝试回答所导致的问题这个问题 In short github 用户尝试这样做git pull rebase并且该用户的本地文件已被删除 我尝试在 github 上重新创建这个场景 但在我的例子中没有删除任何内容 那么如何重现
  • C: printf 一个浮点值

    我想打印一个浮点值 该值在逗号后有 2 个整数和 6 个小数位 如果我只是使用printf f myFloat 我得到了一个被截断的值 我不知道这是否总是发生在 C 语言中 或者只是因为我使用 C 语言作为微控制器 确切地说是 CCS 但在
  • 如何在 Android 中调出锁屏?

    我想在单击按钮时调出设备的锁定屏幕 我搜索了很多并且知道可以通过DevicePolicyManager但不知道该怎么做 我还找到了很多例子 但它们都没有打开锁屏 没有错误 例如this or this 如何使用锁定设备DevicePolic
  • 如何在Python中计算One Class SVM的AUC?

    我在 python 中绘制 OneClassSVM 的 AUC 图时遇到困难 我使用 sklearn 生成混淆矩阵 例如 tp fp fn tn with fn tn 0 from sklearn metrics import roc cu
  • Grunt imagemin正在运行但不缩小

    Image min 运行正常 但我得到 0 个缩小的图像 为什么 在我的终端上运行代码后 grunt imagemin Running imagemin dist imagemin task Minified 0 images saved
  • 如何在 Laravel 5.0 中使用外全连接?

    这是我的控制器 public function lihatpesanansemua ajax if Request ajax hasil DB table pesanan gt join pemesan pemesan id pesanan
  • 解析字段名不一致的JSON字符串

    我在反序列化以下 JSON 结构时遇到问题 每个节点包含一个 ID 和带有值的多语言代码 语言属性的数量并不一致 但我需要这些值作为具有语言字段和值字段的对象列表 id w 312457 eng deep fat frying ger Fr
  • 需要帮助在单个单元格中获取多个值,并在 Excel 中满足条件

    我需要帮助来获取单个单元格中的值并满足条件 我想要单个单元格中的值低于 95 的违约者 e g 如果有动态数组公式 FILTER 和 TEXTJOIN TEXTJOIN CHAR 10 TRUE FILTER A2 A7 E2 E7 lt
  • 如何在 iOS 应用程序中以编程方式创建 PDF 文件?

    如何根据用户操作生成 PDF 文件 See 用石英画画 了解如何创建 PDF 图形上下文 一些注意事项 iPhoneOS注意 如果您想在 iPhone 应用程序中创建 PDF 图形上下文 请确保您还阅读了 在 iPhone OS 中绘制到图
  • 在 C# 中使用 AES 加密

    Locked 这个问题及其答案是locked因为这个问题是题外话 但却具有历史意义 目前不接受新的答案或互动 我似乎找不到使用 AES 128 位加密的清晰示例 有人有一些示例代码吗 如果您只想使用内置加密提供程序 RijndaelMana