加密失败

时间:2019-02-07 16:42:04

标签: c# encryption aes

我最近将以前的加密程序从Java转换为C#。解密功能可以正常工作(使用Java加密的字符串进行测试),但是加密会产生Java程序或C#程序都无法解码的结果。下面包括代码和单元测试以及输出。 GetKey()函数是我自己的盐生成键,可以为给定的输入正确生成相同的键(在Java和C#中进行测试)。

加密和解密功能完全是对偶。我不明白为什么一个有效,而另一个无效。

为了避免Java和C#之间的符号陷阱,我将所有文本都缩减为base64。在解密函数中插入了Java加密的字符串(通过调试器),效果很好。加密的字符串在解密及其Java版本中均无法解码,并且具有相同的错误

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Timers;

namespace Krypto
{
    class Program
    {
        static void Main(string[] args)
        {
        string text;
        string key;
        string encrypText;
        string decryptText;

        Console.Write("Plese enter text to encrypt:");
        text = Console.ReadLine();

        Console.WriteLine("");

        Console.Write("Plese enter Key:");
        key = Console.ReadLine();
        Console.WriteLine("");

        encrypText = EncryptString(text, key);
        Console.WriteLine("The encrypted string is: "+ encrypText);

        decryptText = Decrypt(encrypText, key);
        Console.WriteLine("The decrypted string is: " + decryptText);

        if (text.Equals(decryptText)) Console.WriteLine("The test was sucessful");
        else Console.WriteLine("The test failed!");

        Console.ReadKey();

        }


        static string EncryptString(string text, string key)
        {
            byte[] key16 = getKey16(key);
            string text64 = System.Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(text));
            byte[] encrypted;

            byte[] ivArr = { 1, 3, 3, 4, 5, 6, 6, 7, 4, 3, 2, 1, 7, 5, 5, 7 };
            byte[] IVBytes16Value = new byte[16];
            Array.Copy(ivArr, IVBytes16Value, 16);

        // Create an RijndaelManaged object 
        // with the specified key and IV. 
        using (RijndaelManaged aes = new RijndaelManaged())
            {
                aes.Key = key16; 
                aes.IV = IVBytes16Value;
                aes.BlockSize = 128;
                aes.KeySize = 256;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7; 


            // Create a decryptor to perform the stream transform.
            ICryptoTransform encryptor = aes.CreateEncryptor();

            try
            {
                byte[] textBytes = Convert.FromBase64CharArray(text64.ToCharArray(), 0, text64.Length);
                encrypted = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
                return "";
            };

        }


            // Return the encrypted bytes from the memory stream. 
            return Convert.ToBase64String(encrypted); 

        }

    private static string Decrypt(string CipherText, string key)
    {
        byte[] key16 = getKey16(key);
        RijndaelManaged aes = new RijndaelManaged();
        aes.BlockSize = 128;
        aes.KeySize = 256;

        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        byte[] ivArr = { 1, 3, 3, 4, 5, 6, 6, 7, 4, 3, 2, 1, 7, 5, 5, 7 };
        byte[] IVBytes16Value = new byte[16];
        Array.Copy(ivArr, IVBytes16Value, 16);

        aes.Key = key16;
        aes.IV = IVBytes16Value;

        ICryptoTransform decrypto = aes.CreateDecryptor();
        byte[] decryptedData = null;

        try
        {
            byte[] encryptedBytes = Convert.FromBase64CharArray(CipherText.ToCharArray(), 0, CipherText.Length);
            decryptedData = decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
            return ""; 
        };
            return System.Text.ASCIIEncoding.UTF8.GetString(decryptedData);
        }

    }

private static byte[] getKey16(string key)
        {
            byte[] key16 = new byte[16];
            //make key a 64bit string
            string base64key = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(key));
            byte[] keyArr = Convert.FromBase64String(base64key);

            int keyarraysize = keyArr.Count();

            if (keyarraysize < 16)
            {
                int counter = 0;
                while (keyarraysize * (counter + 1) < 16)
                {
                    for (int i = 0; i < keyarraysize; ++i) key16[i + keyarraysize * counter] = keyArr[i];
                    ++counter;
                }
                for (int i = keyarraysize * counter; i < 16; ++i)
                {
                key16[i] = 0; 
                }
            }
            else for (int i = 1; i < 16; ++i) key16[i] = keyArr[i];
            return key16;

        }
}

C#中的加密和解密完全是对偶。它应该只是产生一个正确的测试,相反我得到下面的输出

请输入要加密的文本:这是一个测试

请输入Key:testKey

加密的字符串是:vLCR4QCJcVHvN4ss7H4Q2g == 错误:填充无效,无法删除。 解密后的字符串为: 测试失败!

1 个答案:

答案 0 :(得分:1)

如果设置KeySize,则密钥将设置为null(将生成随机密钥)。

请参见source

实际上,您不需要设置KeySize,因为该程序知道如何根据密钥进行计算。