首先引入bcprov-ext-jdk14-140.jar这个包,可以从http://www.bouncycastle.org上下载,下面是代码
/**
* 加密工具类
*/
package net.risesoft.platform.util;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.IDEAEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;
/**
* 加密工具类
*
* @author xiaosong
*
*/
public class IDEAEncrypt
{
private PaddedBufferedBlockCipher cipher = null;
/**
* 密钥的长度
*/
private int keylength;
/**
* 设置Block Cipher的加密引擎, 如IDEA_Engine
*
* @param block_cipher_engine
* 加密引擎
*/
public void setEngine(BlockCipher block_cipher_engine)
{
/*
* Setup the DESede cipher engine, create a PaddedBufferedBlockCipher in
* CBC mode.
*/
cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
block_cipher_engine));
}
/**
* 设置Block Cipher的密钥长度
*
* @param length
*/
public void setKeyLength(int length)
{
this.keylength = length;
}
/**
* 设置密钥
*
* @param encrypt
* 加密还是解密
* @param keyStr
* 密钥字符串
*/
public void init(boolean encrypt, String keyStr)
{
/**
* 初始化密钥
*/
byte[] keybyte = new byte[this.keylength];
keybyte = Hex.decode(keyStr);// 将密钥加密
/**
* encrypt = true 加密 encrypt = false 解密
*/
cipher.init(encrypt, new KeyParameter(keybyte));
}
/**
* 加密
*
* @param 要加密的字符串
* @return 加密后的密文
*/
public String Encrypt(String mingwen)
{
byte[] inblock = mingwen.getBytes();
byte[] outblock = new byte[cipher.getOutputSize(inblock.length)];
int outL;
String s1 = "";
outL = cipher.processBytes(inblock, 0, inblock.length, outblock, 0);
try
{
outL = cipher.doFinal(outblock, outL);
} catch (CryptoException ce)
{
ce.printStackTrace();
}
byte[] result = Hex.encode(outblock);
s1 = new String(result).trim();
return s1;
}
/**
* 解密
* @param miwen 密文
* @return 明文
*/
public String Decrypt(String miwen)
{
byte[] inblock = null;
byte[] outblock = null;
String s1 = "";
int outL;
inblock = Hex.decode(miwen);
outblock = new byte[cipher.getOutputSize(inblock.length)];
outL = cipher.processBytes(inblock, 0, inblock.length, outblock, 0);
try
{
outL = cipher.doFinal(outblock, outL);
s1 = new String(outblock).trim();
} catch (CryptoException ce)
{
ce.printStackTrace();
}
return s1;
}
public static void main(String[] args)
{
IDEAEncrypt cipherTool = new IDEAEncrypt();
cipherTool.setEngine(new IDEAEngine());
cipherTool.setKeyLength(128);
String keyStr = "838jf84fr8jfdfrgrdgdfg";
cipherTool.init(true, keyStr);
String miwen = cipherTool.Encrypt("1234567890");
System.out.println(miwen);
cipherTool.init(false, keyStr);
System.out.println(cipherTool.Decrypt(miwen));
}
}