java nio应用 aes字符串加密与解密

import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class AESTest {

public static void main(String args[]) {
try {

KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
SecretKey key = keygen.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String str="原始数据";
System.out.println("加密前数据:"+str);
ByteBuffer in = ByteBuffer.wrap(str.getBytes());
ByteBuffer dec = crypt(in, cipher);
dec.position(0);
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
decrypt(dec, cipher);

} catch (Exception e) {
e.printStackTrace();
}
}

//加密方法
public static ByteBuffer crypt(ByteBuffer in, Cipher cipher)
throws IOException, GeneralSecurityException {
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] outBytes = new byte[outputSize];
in.position(0);
ByteBuffer out = null;

outBytes = cipher.doFinal(in.array());
out = ByteBuffer.wrap(outBytes);

System.out.println("加密数据:" + new String(out.array()));
return out;
}

//解密方法
public static void decrypt(ByteBuffer in, Cipher cipher)
throws IOException, GeneralSecurityException {
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] outBytes = new byte[outputSize];
in.position(0);
ByteBuffer out = null;

outBytes = cipher.doFinal(in.array());
out = ByteBuffer.wrap(outBytes);

System.out.println("解密后数据:" + new String(out.array()));
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值