关于遇到的 C# DES 解密出现 "CryptographicException:不正确的数据"
来源:互联网 发布:js获取ip和端口 编辑:程序博客网 时间:2024/05/16 08:44
tomcat中的加密程序需要换到iis中,用起了 C#中的 DESCryptoServiceProvider,上网找了些相关流程写了个类,感觉比java的程序精简。
但测试中发现异常,同一次测试中,加密,解密都正常。但把加密的base64字符串,再另外测试就出现“不正确的数据”的提示。
然后再上网对比了很多,没看到什么不对的地方。程序如下:
using System;using System.Security.Cryptography;using System.Text;namespace Cproject.capp{ public static class Crypt { private static DESCryptoServiceProvider crypt = new DESCryptoServiceProvider(); private static bool bInit = false; public static void init() { if (bInit == false) { bInit = true; //crypt.IV = Encoding.UTF8.GetBytes("87654321"); //这里需要添加一行 crypt.Key = Encoding.UTF8.GetBytes("12345678"); crypt.Mode = CipherMode.CBC; crypt.Padding = PaddingMode.PKCS7; } } public static String encrypt(String str) { init(); //用UTF-8编码,转为byte[] byte[] bysData = Encoding.UTF8.GetBytes(str); //因為PaddingMode.None的關係, byte[]的長度要是8的倍數 //byte[] bysFixSizeData = new byte[(int)Math.Ceiling(bysData.Length / 8.0) * 8]; //將資料複製到長度為8的倍數的byte[] //Array.Copy(bysData, bysFixSizeData, bysData.Length); //进行加密 byte[] bysEncrypted = crypt.CreateEncryptor().TransformFinalBlock(bysData, 0, bysData.Length); //將byte[]轉為Base64的字串 return Convert.ToBase64String(bysEncrypted); } public static String decrypt(String str) { init(); byte[] bysData = Convert.FromBase64String(str); //进行解密 byte[] bysDecrypted = crypt.CreateDecryptor().TransformFinalBlock(bysData, 0, bysData.Length); return Encoding.UTF8.GetString(bysDecrypted); } }}
若要解密使用其中一个 SymmetricAlgorithm 类加密的数据,必须将 Key 属性和 IV 属性设置为用于加密的相同值。
测试终于成功通过。
- 关于遇到的 C# DES 解密出现 "CryptographicException:不正确的数据"
- .Net使用DES解密发生“数据不正确”的错误
- C#的des加密解密
- C# 的 DES 加密解密
- 用 Java 解密 C# 加密的数据(DES)
- DES加密和解密遇到的问题
- 加密解密时遇到的"不正确的数据"以及"要解密的数据长度无效"问题解决方案
- RSA 加密解密-不正确的数据2
- C#的DES加密解密算法【vs2005】
- c#中DES加密解密的类
- C#的DES加密解密算法
- C#的DES加密解密算法【vs2005】
- C#的3DES加密/解密
- C#的DES加密解密算法
- C#中DES的16进制加解密
- 使用C# DES解密java DES加密的字符串
- 使用C# DES解密java DES加密的字符串
- 关于des文件的加密,解密。
- mysql的常用命令备份表
- Square走入艺术博览会以及农贸市场
- 关于listview获取内部checkbox状态的解决办法
- object-c date类转换成字符串
- Vim For PHP IDE
- 关于遇到的 C# DES 解密出现 "CryptographicException:不正确的数据"
- android 检查能否上网
- FontStyleTestActivity
- FTP上传控件
- DataGridView 说明
- Apache Commons Collections
- sql语句中的count
- 经典排序算法之实现(三)
- Linux下卸载DB2