AES加密 对应的 C#/JAVA 方法
由于最近在项目中用到,之前在网上找了好多,来来回回,终于整出来了。 贴出来以后用起来方便 C# [csharp] view plaincopyprint?
#region AES加解密
/// <summary>
///AES加密(加密步骤)
///1,加密字符串得到2进制数组;
///2,将2禁止数组转为16进制;
///3,进行base64编码
/// </summary>
/// <param name="toEncrypt">要加密的字符串</param>
/// <param name="key">密钥</param>
public String Encrypt(String toEncrypt, String key)
{
Byte[] _Key = Encoding.ASCII.GetBytes(key);
Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt); Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _Key;
ICryptoTransform cTransform = aes.CreateEncryptor();
Byte[] cryptData = cTransform.TransformFinalBlock(_Source, , _Source.Length);
String HexCryptString = Hex_2To16(cryptData);
Byte[] HexCryptData = Encoding.UTF8.GetBytes(HexCryptString);
String CryptString =Convert.ToBase64String(HexCryptData);
return CryptString;
} /// <summary>
/// AES解密(解密步骤)
/// 1,将BASE64字符串转为16进制数组
/// 2,将16进制数组转为字符串
/// 3,将字符串转为2进制数据
/// 4,用AES解密数据
/// </summary>
/// <param name="encryptedSource">已加密的内容</param>
/// <param name="key">密钥</param>
public String Decrypt(string encryptedSource, string key)
{
Byte[] _Key = Encoding.ASCII.GetBytes(key);
Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _Key;
ICryptoTransform cTransform = aes.CreateDecryptor(); Byte[] encryptedData = Convert.FromBase64String(encryptedSource);
String encryptedString = Encoding.UTF8.GetString(encryptedData);
Byte[] _Source = Hex_16To2(encryptedString);
Byte[] originalSrouceData = cTransform.TransformFinalBlock(_Source, , _Source.Length);
String originalString = Encoding.UTF8.GetString(originalSrouceData);
return originalString;
} /// <summary>
/// 2进制转16进制
/// </summary>
String Hex_2To16(Byte[] bytes)
{
String hexString = String.Empty;
Int32 iLength = ;
if (bytes != null)
{
StringBuilder strB = new StringBuilder(); if (bytes.Length < iLength)
{
iLength = bytes.Length;
} for (int i = ; i < iLength; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
} /// <summary>
/// 16进制转2进制
/// </summary>
Byte[] Hex_16To2(String hexString)
{
if ((hexString.Length % ) != )
{
hexString += " ";
}
Byte[] returnBytes = new Byte[hexString.Length / ];
for (Int32 i = ; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * , ), );
}
return returnBytes;
}
#endregion #region AES加解密
/// <summary>
///AES加密(加密步骤)
///1,加密字符串得到2进制数组;
///2,将2禁止数组转为16进制;
///3,进行base64编码
/// </summary>
/// <param name="toEncrypt">要加密的字符串</param>
/// <param name="key">密钥</param>
public String Encrypt(String toEncrypt, String key)
{
Byte[] _Key = Encoding.ASCII.GetBytes(key);
Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt); Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _Key;
ICryptoTransform cTransform = aes.CreateEncryptor();
Byte[] cryptData = cTransform.TransformFinalBlock(_Source, , _Source.Length);
String HexCryptString = Hex_2To16(cryptData);
Byte[] HexCryptData = Encoding.UTF8.GetBytes(HexCryptString);
String CryptString =Convert.ToBase64String(HexCryptData);
return CryptString;
} /// <summary>
/// AES解密(解密步骤)
/// 1,将BASE64字符串转为16进制数组
/// 2,将16进制数组转为字符串
/// 3,将字符串转为2进制数据
/// 4,用AES解密数据
/// </summary>
/// <param name="encryptedSource">已加密的内容</param>
/// <param name="key">密钥</param>
public String Decrypt(string encryptedSource, string key)
{
Byte[] _Key = Encoding.ASCII.GetBytes(key);
Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _Key;
ICryptoTransform cTransform = aes.CreateDecryptor(); Byte[] encryptedData = Convert.FromBase64String(encryptedSource);
String encryptedString = Encoding.UTF8.GetString(encryptedData);
Byte[] _Source = Hex_16To2(encryptedString);
Byte[] originalSrouceData = cTransform.TransformFinalBlock(_Source, , _Source.Length);
String originalString = Encoding.UTF8.GetString(originalSrouceData);
return originalString;
} /// <summary>
/// 2进制转16进制
/// </summary>
String Hex_2To16(Byte[] bytes)
{
String hexString = String.Empty;
Int32 iLength = ;
if (bytes != null)
{
StringBuilder strB = new StringBuilder(); if (bytes.Length < iLength)
{
iLength = bytes.Length;
} for (int i = ; i < iLength; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
} /// <summary>
/// 16进制转2进制
/// </summary>
Byte[] Hex_16To2(String hexString)
{
if ((hexString.Length % ) != )
{
hexString += " ";
}
Byte[] returnBytes = new Byte[hexString.Length / ];
for (Int32 i = ; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * , ), );
}
return returnBytes;
}
#endregion
JAVA: [java] view plaincopyprint?
/**
* 加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
throw new IllegalArgumentException("Argument sKey is null.");
}
if (sKey.length() != ) {
throw new IllegalArgumentException(
"Argument sKey'length is not 16.");
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
String tempStr = parseByte2HexStr(encrypted); Base64Encoder encoder = new Base64Encoder();
return encoder.encode(tempStr.getBytes("UTF-8"));
} /**
*解密--先 进行base64解码,在进行16进制转为2进制然后再解码
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String decrypt(String sSrc, String sKey) throws Exception { if (sKey == null) {
throw new IllegalArgumentException("");
}
if (sKey.length() != ) {
throw new IllegalArgumentException("");
} byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec); Base64Encoder encoder = new Base64Encoder();
byte[] encrypted1 = encoder.decode(sSrc); String tempStr = new String(encrypted1, "utf-8");
encrypted1 = parseHexStr2Byte(tempStr);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} /**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = ; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == ) {
hex = '' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
} /**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < )
return null;
byte[] result = new byte[hexStr.length() / ];
for (int i = ; i < hexStr.length() / ; i++) {
int high = Integer.parseInt(hexStr.substring(i * , i * + ), );
int low = Integer.parseInt(hexStr.substring(i * + , i * + ),
);
result[i] = (byte) (high * + low);
}
return result;
} /**
* 加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
throw new IllegalArgumentException("Argument sKey is null.");
}
if (sKey.length() != ) {
throw new IllegalArgumentException(
"Argument sKey'length is not 16.");
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
String tempStr = parseByte2HexStr(encrypted); Base64Encoder encoder = new Base64Encoder();
return encoder.encode(tempStr.getBytes("UTF-8"));
} /**
*解密--先 进行base64解码,在进行16进制转为2进制然后再解码
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String decrypt(String sSrc, String sKey) throws Exception { if (sKey == null) {
throw new IllegalArgumentException("");
}
if (sKey.length() != ) {
throw new IllegalArgumentException("");
} byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec); Base64Encoder encoder = new Base64Encoder();
byte[] encrypted1 = encoder.decode(sSrc); String tempStr = new String(encrypted1, "utf-8");
encrypted1 = parseHexStr2Byte(tempStr);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} /**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = ; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == ) {
hex = '' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
} /**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < )
return null;
byte[] result = new byte[hexStr.length() / ];
for (int i = ; i < hexStr.length() / ; i++) {
int high = Integer.parseInt(hexStr.substring(i * , i * + ), );
int low = Integer.parseInt(hexStr.substring(i * + , i * + ),
);
result[i] = (byte) (high * + low);
}
return result;
}
AES加密 对应的 C#/JAVA 方法的更多相关文章
- AES加密时抛出java.security.InvalidKeyException: Illegal key size or def
原文:AES加密时抛出java.security.InvalidKeyException: Illegal key size or def 使用AES加密时,当密钥大于128时,代码会抛出 java. ...
- Java aes加密C#解密的取巧方法
摘要: 项目开发过程中遇到一个棘手的问题:A系统使用java开发,通过AES加密数据,B系统使用C#开发,需要从A系统获取数据,但在AES解密的时候遇到麻烦.Java的代码和C#的代码无法互通. Ja ...
- Php AES加密、解密与Java互操作的问题
国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html 内部邀请码:C8E245J (不写邀请码,没有现金送) 国 ...
- AES加密时抛出java.security.InvalidKeyException: Illegal key size or default parametersIllegal key size or default parameters
使用AES加密时,当密钥大于128时,代码会抛出java.security.InvalidKeyException: Illegal key size or default parameters Il ...
- AES加密 Pkcs7 (BCB模式) java后端版本与JS版本对接
1.BCB模式是需要设置iv偏移量和Key值,这两个值就像账号和密码一样,当这两个值一致时才能确保加密和解密的数据一致.(ps:这两个值千万不能暴露出去哦!) 2.JAVA版本代码: 这里的iv偏移量 ...
- AES 加密256位 错误 java.security.InvalidKeyException: Illegal key size or default parameters
Java发布的运行环境包中的加解密有一定的限制.比如默认不允许256位密钥的AES加解密,解决方法就是修改策略文件. 官方网站提供了JCE无限制权限策略文件的下载: JDK8的下载地址: http:/ ...
- java AES加密、解密(兼容windows和linux)
java AES加密.解密 CreationTime--2018年7月14日10点06分 Author:Marydon 1.准备工作 updateTime--2018年8月10日15点28分 up ...
- java代码实现python2中aes加密经历
背景: 因项目需要,需要将一个python2编写的aes加密方式改为java实现. 1.源python2实现 from Crypto.Cipher import AES from binascii i ...
- PHP、Java对称加密中的AES加密方法
PHP AES加密 <?php ini_set('default_charset','utf-8'); class AES{ public $iv = null; public $key = n ...
随机推荐
- iOS 应用上传所需 Icon图片大小
iPhone-only Apps Include the following in your application's Resources group in the Xcode project: T ...
- Android拍照+方形剪裁——附代码与效果图
本文链接 http://blog.csdn.net/xiaodongrush/article/details/29173567 參考链接 http://stackoverflow.com/ ...
- SettingsSVNPlugin
迁移时间:2017年5月20日11:24:50CreateTime--2016年9月18日17:53:20Author:Marydonmyeclipse/eclipse中配置svn插件参考链接:h ...
- 在Loadrunner中如何用system函数执行系统命令
前提: windows 系统 实现功能:用 LR 中的system函数执行系统命令 相关功能:在LR中利用C函数建立文件,写文件,读文件. 主要相关函数:sprintf/fopen/fgetc/fre ...
- 公钥私钥与SSL的握手协议(转)
一,公钥私钥1,公钥和私钥成对出现2,公开的密钥叫公钥,只有自己知道的叫私钥3,用公钥加密的数据只有对应的私钥可以解密4,用私钥加密的数据只有对应的公钥可以解密5,如果可以用公钥解密,则必然是对应的私 ...
- linux 使用wc命令统计文件行数、字数及大小
语法:wc [选项] 文件… 说明:该命令统计给定文件中的字节数.字数.行数.如果没有给出文件名,则从标准输入读取.wc同时也给出所有指定文件的总统计数.字是由空格字符区分开的最大字符串. 该命令各选 ...
- 利用ASP.NET一般处理程序动态生成Web图像(转)
摘自:http://www.cnblogs.com/zhouhb/archive/2011/02/15/1955262.html 一般处理程序的扩展名为ashx,它实现了IHttpHandler接口, ...
- Docker基础概念及操作
一.概念: Docker 属于Linux 容器的一种封装,提供简单易用的容器使用接口.目前最流行的Linux 容器解决方案. Docker 将应用程序与该程序的依赖,打包在一个文件里面.运行这个文件, ...
- HDUOJ---(1995)汉诺塔V
汉诺塔V Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submi ...
- C#将Access数据库导出为JSON
一个Access数据库包含若干首诗歌,每首诗有content.author.title.description四个字段 using System; using System.Data; using S ...