C# 实现 加密、解密使用AES算法的OFB模式(不填充,明文与密文长度一致)

SurpassCode 2014-09-09 11:05:56

//默认密钥向量
byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
//加密KEY
byte[] Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
//加密方法
public static byte[] EncryptStringToBytes_Aes(byte[] plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an AesCryptoServiceProvider object
// with the specified key and IV.
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.OFB;
aesAlg.Padding = PaddingMode.None;


// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

// Create the streams used for encryption.
using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
//Write all data to the stream.
csEncrypt.Write(plainText, 0, plainText.Length);
csEncrypt.FlushFinalBlock();

encrypted = msEncrypt.ToArray();
}
}
}

// Return the encrypted bytes from the memory stream.
return encrypted;
}

在 csEncrypt.FlushFinalBlock(); 报错

“System.Security.Cryptography.CryptographicException”类型的异常在 System.Core.dll 中发生,但未在用户代码中进行处理
其他信息: 输入数据不是完整的块。

求解答 如果使用ASE加密算法的OFB模式进行加密
最好能给个栗子!!谢谢

...全文
985 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
绿领巾童鞋 2014-09-10
  • 打赏
  • 举报
回复
http://social.msdn.microsoft.com/Forums/vstudio/en-US/891955cd-3125-487c-9746-9fd07f24b12f/why-net-doesnt-support-aes-ofb?forum=netfxbcl http://stackoverflow.com/questions/24515521/aes-ofb-encryption-for-rijndaelmanaged OFB模式估计要自己写。可以的话,也可以通过DLL调用...
yangbo50304 2014-09-09
  • 打赏
  • 举报
回复
可能是Key和IV的长度错了,你这个是128的还是256的长度?

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧