importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.SecretKey;importorg.apache.commons.codec.binary.Base64;importorg.bouncycastle.jce.provider.BouncyCastleProvider;importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.SecretKey;importjavax.crypto.spec.SecretKeySpec;importjava.security.Key;importjava.security.Security;public class IDEA implementsMethod{public static final String KEY_ALGORITHM="IDEA";public static final String CIPHER_ALGORITHM="IDEA/ECB/ISO10126Padding";public static byte[] initkey() throwsException{//加入bouncyCastle支持
Security.addProvider(newBouncyCastleProvider());//实例化密钥生成器
KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM);//初始化密钥生成器,IDEA要求密钥长度为128位
kg.init(128);//生成密钥
SecretKey secretKey=kg.generateKey();//获取二进制密钥编码形式
returnsecretKey.getEncoded();
}/*** 转换密钥
*@paramkey 二进制密钥
*@returnKey 密钥
**/
private static Key toKey(byte[] key) throwsException{//实例化DES密钥//生成密钥
SecretKey secretKey=newSecretKeySpec(key,KEY_ALGORITHM);returnsecretKey;
}/*** 加密数据
*@paramdata 待加密数据
*@paramkey 密钥
*@returnbyte[] 加密后的数据
**/
private static byte[] encrypt(byte[] data,byte[] key) throwsException{//加入bouncyCastle支持
Security.addProvider(newBouncyCastleProvider());//还原密钥
Key k=toKey(key);//实例化
Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);//初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, k);//执行操作
returncipher.doFinal(data);
}/*** 解密数据
*@paramdata 待解密数据
*@paramkey 密钥
*@returnbyte[] 解密后的数据
**/
private static byte[] decrypt(byte[] data,byte[] key) throwsException{//加入bouncyCastle支持
Security.addProvider(newBouncyCastleProvider());//还原密钥
Key k =toKey(key);
Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);//初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, k);//执行操作
returncipher.doFinal(data);
}public staticString getKey(){
String result= null;try{
result=Base64.encodeBase64String(initkey());
}catch(Exception e) {
e.printStackTrace();
}returnresult;
}public staticString ideaEncrypt(String data, String key) {
String result= null;try{byte[] data_en =encrypt(data.getBytes(), Base64.decodeBase64(key));
result=Base64.encodeBase64String(data_en);
}catch(Exception e) {
e.printStackTrace();
}returnresult;
}public staticString ideaDecrypt(String data, String key) {
String result= null;try{byte[] data_de =decrypt(Base64.decodeBase64(data), Base64.decodeBase64(key));;
result= newString(data_de);
}catch(Exception e) {
e.printStackTrace();
}returnresult;
}public voidwork(String str,String password,String data) {
String key=getKey();
System.out.println("要加密的原文:"+data);
System.out.println("密钥:" +key);
String data_en=ideaEncrypt(data, key);
System.out.println("密文:"+data_en);
String data_de=ideaDecrypt(data_en, key);
System.out.println("原文:"+data_de);
}
}