C# 填充无效,无法被移除
1.本文采用微软的
RijndaelManaged
- Assemblies:
- mscorlib.dll, netstandard.dll, System.Security.Cryptography.Algorithms.dll
访问的托管的版本Rijndael算法。 此类不能被继承。
实现加密解密,
查看代码:
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 <= )
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= )
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= )
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 an encryptor 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 <= )
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= )
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= )
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 decryptor 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; }
}
}
这个加密乃 微软官方案例。毛的问题
下面这个是错误的代码
[Fact(DisplayName ="")]
public void stat()
{
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);
myRijndael.GenerateKey();
myRijndael.GenerateIV();
// 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);
}
} /// <summary>
///
/// </summary>
/// <param name="plainText"></param>
/// <param name="Key"></param>
/// <param name="IV"></param>
/// <returns></returns>
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= )
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= )
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= )
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 an encryptor 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; } /// <summary>
///
/// </summary>
/// <param name="cipherText"></param>
/// <param name="Key"></param>
/// <param name="IV"></param>
/// <returns></returns>
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= )
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= )
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= )
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 decryptor 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; }
我把唯一改动测试的地方做了个标记。因为加密前随机的key 跟解密后的key 不一致,所以导致了这个错误
防止踩坑,以及知道这个玩意的原理。
C# 填充无效,无法被移除的更多相关文章
- .net 加密错误:填充无效,无法移除
今天用System.Security.Cryptography加密.使用了AesManaged,报错:填充无效,无法移除.分析是解密失败,密文损坏,或者KEY,IV不正确. using (AesMan ...
- 解决解密时出现"要解密的数据的长度无效" 或 "填充无效无法被移除" 的错误
1.首先排除数据库中读取加密后的字段是否被强制截断. 2.AES加密后的byte[]首先应用base64( Convert.ToBase64String)编码一次,若直接用utf8的话会报上述错误,若 ...
- 微信小程序加密解密 C# 以及 填充无效,无法被移除错误的解决方案 Padding is invalid and cannot be removed
解密加密源码 using System; using System.Security.Cryptography; using System.Text; namespace Wechat { publi ...
- C# .net 填充无效,无法被移除 微信小程序解密失败的解决办法
微信小程序获取用户信息诸如unionId的时候需要解密,如果遇到偶然的解密失败(填充无效,无法被移除),原因很有可能是session_key错误, 也是就你用作解密的session_key并不是微信用 ...
- ThinkPHP 自动验证与自动填充无效可能的原因(转)
自动验证与自动填充是在使用ThinkPHP时经常用到的功能,但偶尔会遇到自动验证与自动填充无效的情况,本文就ThinkPHP 自动验证与自动填充无效可能的原因做一些分析. create() Think ...
- ThinkPHP 自动验证与自动填充无效可能的原因
原文链接:http://www.5idev.com/p-thinkphp_validate_auto_Invalid.shtml 自动验证与自动填充是在使用ThinkPHP时经常用到的功能,但偶尔会遇 ...
- http2协议翻译(转)
超文本传输协议版本 2 IETF HTTP2草案(draft-ietf-httpbis-http2-13) 摘要 本规范描述了一种优化的超文本传输协议(HTTP).HTTP/2通过引进报头字段压缩以及 ...
- GDI编程
图形设备接口(GDI)是一个可执行程序,它接受Windows应用程序的绘图请求(表现为GDI函数调用),并将它们传给相应的设备驱动程序,完成特定于硬件的输出,象打印机输出和屏幕输出.GDI负责Wind ...
- WPS客户端更新日志留着备用
WPS Office (10.1.0.7520)==========================================新增功能列表------------WPS文字1 拼写检查:新增“中 ...
随机推荐
- Python实现的选择排序算法原理与用法实例分析
Python实现的选择排序算法原理与用法实例分析 这篇文章主要介绍了Python实现的选择排序算法,简单描述了选择排序的原理,并结合实例形式分析了Python实现与应用选择排序的具体操作技巧,需要的朋 ...
- JAVA 基础编程练习题20 【程序 20 求前 20 项之和】
20 [程序 20 求前 20 项之和] 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前 20 项之和. 程序分析:请抓住分子与分母的变化规律. pac ...
- 读写Session
读写Session Session是保存在服务端的字典 Session与Cookie有些类似,都是通过字典管理key-value对,只不过Cookie是保存在客户端的字典,而Session是保存在服务 ...
- CockroachDB学习笔记——[译]Hello World
原文链接:https://www.cockroachlabs.com/blog/hello-world/ 原作者:Spencer Kimball 原文日期:Jun 4, 2015 译:zifeiy 数 ...
- 基于LSTM + keras 的诗歌生成器
最近在github 上发现了一个好玩的项目,一个基于LSTM + keras 实现的诗歌生成器,地址是:https://github.com/youyuge34/Poems_generator ...
- python 智能玩别踩白块
# encoding :utf-8import pyautoguifrom PIL import Imageimport time pyautogui.FAILSAFE = True time.sle ...
- 记录一次SignalR服务端实现过程
前言:最近手上一个项目需要后端实时推送数据到前端,第一个想到的就是微软的SignalR,由于之前都是平时没事写的Demo,没有用到实际项目中,这次恰好用到了,因此记录下来整个实现过程(网上也有很多类似 ...
- Nginx05---负载均衡 upsteam
参考 https://www.cnblogs.com/linjiqin/p/5494783.html
- 2019牛客多校第七场E Find the median 权值线段树+离散化
Find the median 题目链接: https://ac.nowcoder.com/acm/contest/887/E 题目描述 Let median of some array be the ...
- MS SQL 2012表分区
最近开发一个手机用户统计平台,因为涉及到数据庞大,不得不以一周为单位对统计报表进行分区,所以记录一下,方便以后查看 第一步创建文件分组 对于文件分组共创建了14个,从 xy_group_2014102 ...