Java和C#的AES加解密

兄弟部门的一段Java aes加密逻辑需要在.net环境解密,网上查了一堆都用不了,还是自己写个吧,有句话怎么说来着,自己动手丰衣足食。老惯例文字不够代码凑。

Java版本:

package com.laowang.test;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
* @Description TODO
* @Classname UserDataEncryptUtil
* @Author ruyi.zuo
* @Date 17/02/2020 4:39 PM
* @Version V1.0
*/
public class UserDataEncryptUtil {
private static String USER_DATA_ENCRYPT_KEY = “加密用的key”;
private static String ivParameter = “初始化向量”;

/**
* 加密
* @param data
* @return
*/
public static String encrypt(String data) {
if(data == null) {
return null;
}
try {
Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
byte[] raw = USER_DATA_ENCRYPT_KEY.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, “AES”);
//使用CBC模式,需要一个向量iv,可增加加密算法的强度
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(data.getBytes(“UTF-8”));
return parseByte2HexStr(encrypted);
} catch (Exception e) {
//logger.error(“用户敏感数据加密异常, data:{}, e:”, data, e);
return null;
}
}

/**
* 解密
* @param secretData
* @return
*/
public static String decrypt(String secretData) {
try {
byte[] raw = USER_DATA_ENCRYPT_KEY.getBytes(“UTF-8”);
SecretKeySpec skeySpec = new SecretKeySpec(raw, “AES”);
Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted = parseHexStr2Byte(secretData);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original, “UTF-8”);
return originalString;
} catch (Exception e) {
return null;
}
}

/**
* 将二进制转换成16进制
* @param buf
* @return
*/
private static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = ‘0’ + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}

/**
* 将16进制转换为二进制
* @param hexStr
* @return
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}

public static void main(String[] args) throws Exception {
// 需要加密的字串
String cSrc = “hello world!”;
System.out.println(“加密前的字串是:” + cSrc);
// 加密
String enString = UserDataEncryptUtil.encrypt(cSrc);
System.out.println(“加密后的字串是:” + enString);
System.out.println(“加密后的字串长度:” + enString.length());

// 解密
String DeString = UserDataEncryptUtil.decrypt(enString);
System.out.println(“解密后的字串是:” + DeString);
}
}

 

C#版本:

/// <summary>
/// AES加密
/// </summary>
/// <param name=”pToEncrypt”></param>
/// <param name=”sKey”></param>
/// <param name=”sIV”></param>
/// <returns></returns>
public static string Encrypt(string pToEncrypt, string sKey, string sIV)
{
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = Encoding.ASCII.GetBytes(sKey);
aes.IV = Encoding.ASCII.GetBytes(sIV);

MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();

var ret = new StringBuilder();
foreach (byte b in ms.ToArray())
ret.AppendFormat(“{0:X2}”, b);

return ret.ToString();
}

/// <summary>
/// AES解密
/// </summary>
/// <param name=”pToDecrypt”></param>
/// <param name=”sKey”></param>
/// <param name=”sIV”></param>
/// <returns></returns>
public static string Decrypt(string pToDecrypt, string sKey, string sIV)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}

aes.Key = Encoding.ASCII.GetBytes(sKey);
aes.IV = Encoding.ASCII.GetBytes(sIV);

MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();

return System.Text.Encoding.Default.GetString(ms.ToArray());
}

static void Main(string[] args)
{
var sKey = “加密的key”;
var sIV = “初始化向量”;

var encryptStr = Encrypt(“hello world!”, sKey, sIV);
var decryptStr = Decrypt(encryptStr, sKey, sIV);

Console.WriteLine(encryptStr);
Console.WriteLine(decryptStr);
Console.WriteLine();

来个图结尾:

发表评论

电子邮件地址不会被公开。 必填项已用*标注