1.本文采用微软的

RijndaelManaged

命名空间:
System.Security.Cryptography
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# 填充无效,无法被移除的更多相关文章

  1. .net 加密错误:填充无效,无法移除

    今天用System.Security.Cryptography加密.使用了AesManaged,报错:填充无效,无法移除.分析是解密失败,密文损坏,或者KEY,IV不正确. using (AesMan ...

  2. 解决解密时出现"要解密的数据的长度无效" 或 "填充无效无法被移除" 的错误

    1.首先排除数据库中读取加密后的字段是否被强制截断. 2.AES加密后的byte[]首先应用base64( Convert.ToBase64String)编码一次,若直接用utf8的话会报上述错误,若 ...

  3. 微信小程序加密解密 C# 以及 填充无效,无法被移除错误的解决方案 Padding is invalid and cannot be removed

    解密加密源码 using System; using System.Security.Cryptography; using System.Text; namespace Wechat { publi ...

  4. C# .net 填充无效,无法被移除 微信小程序解密失败的解决办法

    微信小程序获取用户信息诸如unionId的时候需要解密,如果遇到偶然的解密失败(填充无效,无法被移除),原因很有可能是session_key错误, 也是就你用作解密的session_key并不是微信用 ...

  5. ThinkPHP 自动验证与自动填充无效可能的原因(转)

    自动验证与自动填充是在使用ThinkPHP时经常用到的功能,但偶尔会遇到自动验证与自动填充无效的情况,本文就ThinkPHP 自动验证与自动填充无效可能的原因做一些分析. create() Think ...

  6. ThinkPHP 自动验证与自动填充无效可能的原因

    原文链接:http://www.5idev.com/p-thinkphp_validate_auto_Invalid.shtml 自动验证与自动填充是在使用ThinkPHP时经常用到的功能,但偶尔会遇 ...

  7. http2协议翻译(转)

    超文本传输协议版本 2 IETF HTTP2草案(draft-ietf-httpbis-http2-13) 摘要 本规范描述了一种优化的超文本传输协议(HTTP).HTTP/2通过引进报头字段压缩以及 ...

  8. GDI编程

    图形设备接口(GDI)是一个可执行程序,它接受Windows应用程序的绘图请求(表现为GDI函数调用),并将它们传给相应的设备驱动程序,完成特定于硬件的输出,象打印机输出和屏幕输出.GDI负责Wind ...

  9. WPS客户端更新日志留着备用

    WPS Office (10.1.0.7520)==========================================新增功能列表------------WPS文字1 拼写检查:新增“中 ...

随机推荐

  1. Java的三种工厂模式

    一.简单工厂模式 简单工厂的定义:提供一个创建对象实例的功能,而无须关心其具体实现.被创建实例的类型可以是接口.抽象类,也可以是具体的类 实现汽车接口 //产品接口 //汽车需要满足一定的标准 pub ...

  2. Linux云服务器磁盘不见了?解决方案在这里,云服务器磁盘挂载

    用过诸多种云以后,发现有个通病,就是新买的数据盘在机器中找不到.本篇总结一下此类问题的解决方法,望各位点赞,有问题评论区见 一.云服务和物理机一样,你买了云服务器的数据盘以后,就相当于把数据盘直接安装 ...

  3. linux安装IDEA 2017

    下载 IDEA 2017 链接:http://pan.baidu.com/s/1skTKdFR 密码:yug3 解压 下载的文件    tar zxvf idea-IU-172.4155.36.tar ...

  4. Python操作qml对象

    1. 如何在python里获得qml里的对象? 1.1 获取根对象 QML: import QtQuick 2.12 import QtQuick.Controls 2.12 ApplicationW ...

  5. socket之IO多路复用

    概述 目的:同一个线程同时处理多个IO请求. 本文以python的select模块来实现socket编程中一个server同时处理多个client请求的问题. web框架tornado就是以此实现多客 ...

  6. Docker部署WordPress网站

    WordPress是使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站,WordPress 不仅仅是一个博客程序,也是一款CMS,很多非博客网站也是用Wo ...

  7. 51nod1050 循环数组最大子段和

    思路: 分两种情况讨论. 实现: #include <bits/stdc++.h> using namespace std; typedef long long ll; ; ll sum[ ...

  8. Golang中string和[]byte的对比

    golang string和[]byte的对比 为啥string和[]byte类型转换需要一定的代价? 为啥内置函数copy会有一种特殊情况copy(dst []byte, src string) i ...

  9. mysql根据时间统计数据语句

    select FROM_UNIXTIME(`createtime`, '%Y年%m月%d日')as retm,count(*) as num  from `user` GROUP BY retm se ...

  10. Linux下运行《UNIX环境高级编程》undefined reference to `err_quit 编译出错的处理方法

    错误信息: : undefined reference to `err_quit': undefined reference to `err_sys' 解决方法: 因为err_quit跟err_sys ...