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 拼写检查:新增“中 ...
随机推荐
- MySQL连接错误:Can't connect to MySQL server on'localhost' (10055)
在Windows服务器上确认服务器和mysql都是正常运行,但就是连接不上.搜了一下别人的解决方案, 参考这篇https://blog.csdn.net/langren697/article/deta ...
- 查看进程的命令ps
查看进程的命令:ps aux strace -p pid(进程id) 杀死进程:kill pid(进程id)强制杀死进程:kill -9 pid(进程id) linux ps 命令查看进程状态linu ...
- 解决Unity3d 图片黑边问题
突然发现UI有黑边,在Photoshop里面没发现问题. 最后在图集的属性中去掉Minimap选项就可以了.
- 【FICO系列】SAP FI验证故障排除(调试)
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[FICO系列]SAP FI验证故障排除(调试) ...
- PJzhang:docker基础知识的2个疗程-one
猫宁!!! 参考:http://virtual.51cto.com/art/201805/572135.htm https://www.cnblogs.com/rkit/p/9237696.html ...
- 深度优先dfs与广度bfs优先搜索总结+例题
DFS(Deep First Search)深度优先搜索 深度优先遍历(dfs)是对一个连通图进行遍历的算法.它的思想是从一个顶点开始,沿着一条路一直走到底,如果发现不能到达目标解,那就返回到上一个节 ...
- python 智能玩别踩白块
# encoding :utf-8import pyautoguifrom PIL import Imageimport time pyautogui.FAILSAFE = True time.sle ...
- 【转】MySql 三大知识点——索引、锁、事务
索引 索引,类似书籍的目录,可以根据目录的某个页码立即找到对应的内容. 索引的优点:1. 天生排序.2. 快速查找. 索引的缺点:1. 占用空间.2. 降低更新表的速度. 注意点:小表使用全表扫描更快 ...
- 2019秋JAVA第三周课程总结及实验报告(二)
个人博客 一.基础字符串操作 题目:已知字符串:"this is a test of java".按要求执行以下操作:(要求源代码.结果截图.) 统计该字符串中字母s出现的次数. ...
- Vue代码分割懒加载的实现方法
什么是懒加载 懒加载也叫延迟加载,即在需要的时候进行加载,随用随载. 为什么需要懒加载 在单页应用中,如果没有应用懒加载,运用webpack打包后的文件将会异常的大,造成进入首页时,需要加载的内容过多 ...