JAVA和C通讯的AES加密和解密,供参考


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

/**
* 自己做的JAVA和C通讯的AES加密和解密,供参考
* @author yaodaqing
*
*/
public class AESAndC02 {

/**
* 密钥
*/
private static final String aesKey = "0123456789abcdef";

/**
* 加密
* @param b
* @return
*/
public static byte[] encryptAES(byte[] b){
if (aesKey == null) {
System.out.print("Key为空null");
return null;
}
//判断Key是否为16位
if (aesKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
try {
byte[] raw = aesKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(b);
return encrypted;
} catch (Exception e) {
System.out.println("数据加密时发生异常...");
e.printStackTrace();
}
return null;
}

/**
* 解密
* @param b
* @return
* 由于C语言在加密时采用了模式,所以JAVA在解析时需要采用模式来解密
*/
public static byte[] decryptAES(byte[] b){
//判断Key是否正确
if (aesKey == null) {
System.out.print("Key为空null");
return null;
}
//判断Key是否为16位
if (aesKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
try {
byte[] raw = aesKey.getBytes("ASCII");
SecretKeySpec skp = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skp);
byte[] original = cipher.doFinal(b);
return original;
} catch (Exception e) {
System.out.println("数据解密时发生异常...");
e.printStackTrace();
}
return null;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值