繁体   English   中英

AES加密C#

[英]AES Encryption C#

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

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

模式:ECB KeySize:256 BlockSize:128填充:PKCS7

我使用的是一个32字节的密钥,它是从文件生成的,也是一个空白的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填充,以便在所有情况下添加填充。 当明文是块大小的倍数时,添加整个填充块。 这就是当明文长度为48字节时密文长度为64字节的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM