package com.enno.food.core.util;
import com.enno.food.core.base.Constants;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import static java.lang.System.out;
public class AesUtil {
/**
* 加密
* @param plainText
* @param salt
* @return
* @throws IOException
* @throws InvalidCipherTextException
*/
public static byte[] encrypt(String plainText,String salt) throws IOException, InvalidCipherTextException {
return transform(true, plainText.getBytes("UTF-8"),salt);
}
/**
* 解密
* @param cipherText
* @param salt
* @return
* @throws IOException
* @throws InvalidCipherTextException
*/
public static byte[] decrypt(byte[] cipherText,String salt) throws IOException, InvalidCipherTextException {
return transform(false,cipherText,salt);
}
private static byte[] transform(boolean encrypt, byte[] inputBytes,String salt) throws IOException, InvalidCipherTextException {
byte[] key = DigestUtils.md5((salt + Constants.KEY).getBytes("UTF-8"));
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
cipher.init(encrypt, new KeyParameter(key));
ByteArrayInputStream input = new ByteArrayInputStream(inputBytes);
ByteArrayOutputStream output = new ByteArrayOutputStream();
int inputLen;
int outputLen;
byte[] inputBuffer = new byte[1024];
byte[] outputBuffer = new byte[cipher.getOutputSize(inputBuffer.length)];
while ((inputLen = input.read(inputBuffer)) > -1) {
outputLen = cipher.processBytes(inputBuffer, 0, inputLen, outputBuffer, 0);
if (outputLen > 0) {
output.write(outputBuffer, 0, outputLen);
}
}
outputLen = cipher.doFinal(outputBuffer, 0);
if (outputLen > 0) {
output.write(outputBuffer, 0, outputLen);
}
return output.toByteArray();
}
public static void main(String[] args) throws IOException, InvalidCipherTextException {
System.out.println(new String(encrypt("中华人民共和国","1232131")));
}
}
java Aes 192 256加密,附jar 说明 AesUtil
5星 · 超过95%的资源 需积分: 43 189 浏览量
2015-01-30
14:37:22
上传
评论
收藏 2.45MB RAR 举报
babata01
- 粉丝: 4
- 资源: 47
- 1
- 2
前往页