前言
- 由于最近有个项目需要对接一个Java开发的接口数据,拿到后有点懵逼,加密解密代码是Java的,看的有点迷,好在有C#的基础,看起来还是知道个大概,但是还是在这个数据解密问题上花了很多精力,主要卡住我的问题就是输出编码错了,经过多天的努力,找遍各大网站,试了无数种方案,最终综合各个网站代码再结合Java的代码完美解决了。
- 下面是我对应整理封装了加密解密的一个类。如果你也遇到类似问题可以参考以下类,自行调整模式实现。
- 有不懂的可以评论留言我。
注意事项
- rijndaelCipher.Mode = CipherMode.ECB;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
此代码表示AES加密模式等,可以根据需要变换对应的值使用。 - ECB模式下不需要IV偏移量。
- 输出编码hex与base64的相关代码切换,代码中已注释说明。
- 在线加密解密工具地址:(自己测试用的) http://tool.chacuo.net/cryptaes
完整代码
using System;
using System.Security.Cryptography;
using System.Text;
namespace MyDemo
{
#region 字符串加密解密
public class AESEncryption
{
#region AES加密
public static string AESEncode(string text, string key)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.ECB;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
len = keyBytes.Length;
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return ToHex(cipherBytes);
}
#endregion
#region AES解密
public static string AESDecode(string text, string key)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.ECB;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = UnHex(text);
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
len = keyBytes.Length;
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
#endregion
#region Hex与byte转码
private static string ToHex(byte[] bytes)
{
string str = string.Empty;
if (bytes != null || bytes.Length > 0)
{
for (int i = 0; i < bytes.Length; i++)
{
str += string.Format("{0:X2}", bytes[i]);
}
}
return str.ToLower();
}
public static byte[] UnHex(string hex)
{
if (hex == null)
throw new ArgumentNullException("hex");
hex = hex.Replace(",", "");
hex = hex.Replace("\n", "");
hex = hex.Replace("\\", "");
hex = hex.Replace(" ", "");
if (hex.Length % 2 != 0)
{
hex += "20";
throw new ArgumentException("hex is not a valid number!", "hex");
}
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
try
{
bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
System.Globalization.NumberStyles.HexNumber);
}
catch
{
throw new ArgumentException("hex is not a valid hex number!", "hex");
}
}
return bytes;
}
#endregion
}
#endregion
}