C#加密填充无效,无法删除 [英] C# cryptography padding is invalid and cannot be removed

查看:89
本文介绍了C#加密填充无效,无法删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello编程员,你好b $ b我最近在C#中使用加密技术做了一些工作。我编译了我的程序以测试算法,我从JIT收到一条错误消息:

Hello fellow coders,
I have recently been doing some work with cryptography in C#. I compiled my program to test the algorithm and I got an error message from JIT saying:

"Padding is invalid and cannot be removed"

我已经查看了很多其他问题有关这方面的互联网,大多数人都说在CryptoStrea上使用FlushFinalBlock方法,但这对我不起作用。这是我的代码:

I have looked at many other questions on the internet about this, and most of them say to use the FlushFinalBlock method on the CryptoStrea, but this isn't working for me. Here is my code:

public static string encodeAES(string input, string key)
{
	MemoryStream mStream = new MemoryStream();
	AesManaged crypto = new AesManaged();
	CryptoStream cStream = new CryptoStream(mStream, crypto.CreateEncryptor(getEncryptionKey(key, keyLength_AES), crypto.IV), CryptoStreamMode.Write);// getEncryptionKey is defined elsewhere and returns a key formatted for AES based of the user's key
	byte[] toEncrypt = new ASCIIEncoding().GetBytes(input); // TODO
	cStream.Write(toEncrypt, 0, toEncrypt.Length);
	cStream.FlushFinalBlock();
	byte[] ret = mStream.ToArray();
	cStream.Close();
	mStream.Close();
	return new ASCIIEncoding().GetString(ret);
}
public static string decodeAES(string input, string key)
{
	MemoryStream msDecrypt = new MemoryStream(GetBytes(input));
	AesManaged crypto = new AesManaged();
	CryptoStream csDecrypt = new CryptoStream(msDecrypt, crypto.CreateDecryptor(getEncryptionKey(key, keyLength_AES), crypto.IV), CryptoStreamMode.Read);// getEncryptionKey is defined elsewhere and returns a key formatted for AES based of the user's key
	byte[] fromEncrypt = new byte[input.Length];
	csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
	return new ASCIIEncoding().GetString(fromEncrypt);
}



好​​像我已经做好了一切,但我仍然从decodeAES方法中得到错误。任何想法/解决方案?非常感谢你的时间!



干杯!

推荐答案

问题几乎肯定是你方法的最后一部分:

The problem is almost certainly the final part of your method:
return new ASCIIEncoding().GetString(ret);

使用任何形式的编码将字节数组转换为字符串可能会为您提供一个无法转换回原始字节数组的字符串。



试一试:不是返回一个字符串,而是使用你的代码生成字符串,然后使用你的补充代码立即生成一个未被激活的字节数组。

然后将原始文件中的每个字节与再生版本中的等效字节进行比较。一个不同的位将足以破坏整个操作。

Converting a byte array to a string using any form of encoding is likely to give you a string that can't be converted back to the original array of bytes.

Try it: instead of returning a string, use your code to generate the string, then use your complementary code to immediately generate a "unstringed" byte array from that.
Then compare each byte in the original with it's equivalent in the "regenerated" version. One single bit different will be enough to scupper the whole operation.


这篇关于C#加密填充无效,无法删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆