AES-ECB-128加密算法

要加密或解密的数据必须是16的倍数。
package com.hx.dlms.cipher;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import cn.hexing.fk.utils.HexDump;

public class AESECB128 {
private static final byte[] staticKey = HexDump.toByteBuffer("00000000000000000000000000000000").array();

public static byte[] encrypt(byte[] plainText) {
return encrypt(plainText,staticKey);
}

/**
* 加密
*
* @param content
* 需要加密的内容
* @param enckey
* 加密密码
* @return
*/
public static byte[] encrypt(byte[] content, byte[] enckey) {
try {
SecretKeySpec key = new SecretKeySpec(enckey, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

public static byte[] decrypt(byte[] cipherText) {
return decrypt(cipherText,staticKey);
}
/**
* 解密
*
* @param content
* 待解密内容
* @param deckey
* 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, byte[] deckey) {
try {
SecretKeySpec key = new SecretKeySpec(deckey, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

public static void main(String[] args) {
String content = "6789:;<=>?@AB012";
String password = "00000000000000000000000000000000";
byte[] mykey = HexDump.toByteBuffer(password).array();
// 加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content.getBytes(), mykey);
System.out.println("cipher text: " + HexDump.hexDumpCompact(encryptResult,0,encryptResult.length));
// 解密
byte[] decryptResult = decrypt(encryptResult, mykey);
System.out.println("解密后:" + new String(decryptResult));
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值