c# - AES 加密 C#

标签 c# encryption aes

编辑:将我的哈希码添加到底部。

我在为我正在创建的解决方案创建消息完整性 key 时遇到了一些问题。为了使其正确,我需要使用以下设置。

模式:欧洲央行 key 大小:256 block 大小:128 填充:PKCS7

我使用的是从文件生成的 32 字节 key 和空白 IV,据我了解 ECB 不需要。

我的问题是在编码之前我期望从中得到 48 字节的输出,但是我收到的是 64 字节的输出。

我在下面展示了一些关于我如何尝试实现这一目标的代码,但我并没有取得太大的成功。

public static string Encrypt(string hash) {

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

            myAes.Key = File.ReadAllBytes("keyfile");
            myAes.Mode = CipherMode.ECB;
            myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            myAes.KeySize = 256;
            myAes.BlockSize = 128;
            myAes.Padding = PaddingMode.PKCS7;

            // Encrypt the string to an array of bytes.
            byte[] encrypted = EncryptStringToBytes_Aes(hash, myAes.Key, myAes.IV);

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

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

            // Encode
            string encoded = Convert.ToBase64String(encrypted);

            Console.WriteLine("Encoded:    {0}", encoded);
            return encoded;
        }
    }

    static byte[] EncryptStringToBytes_Aes(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("Key");
        byte[] encrypted;
        // Create an AesManaged object
        // with the specified key and IV.
        using (AesManaged aesAlg = new AesManaged()) {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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_Aes(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("Key");

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

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

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.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;

    }

        public static string getHashSha256(string text) {
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        foreach (byte x in hash) {
            hashString += String.Format("{0:x2}", x);
        }
        return hashString;
    }

最佳答案

PKCS #7 填充被定义为在所有情况下都添加填充。当明文是 block 大小的倍数时,添加一整 block 填充。这就是为什么当明文长度为 48 字节时,密文长度为 64 字节的原因。

关于c# - AES 加密 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17853064/

相关文章:

reactjs - 如何在 React Native 中加密数据(使用 Expo)

c# - Silverlight:为什么这个绑定(bind)表达式不起作用?

c# - 用于离屏渲染器的 XNA 与 SlimDX

c# - 在 .net Web 服务中使用 log4net

C# 按 String[] 分隔符拆分,仅匹配精确单词

iOS sqlcipher fmdb “File is encrypted or is not a database”

encryption - 保护和验证从服务器到客户端的数据

security - 在 Github 存储库中存储 SSL .key 文件的标准是什么?

node.js - 使用 Crypto 时 NodeJS 解密失败。有什么问题吗?

ios - AES/cbc/pkcs5padding加密IOS