日期:2014-05-20  浏览次数:20726 次

[紧急求助] JAVA 3DES加密问题
以3DES按ECB模式加密算法加密字符串,然后用BASE64算法和URLEncoding算法进行编码

以下是我的代码,拿了别人的例子测下了,不对!!不知道哪有问题,望高人指点:

public class ECB
{
/**

* @param str 要加密的字符串
* @param materialKey 密钥
* @return
*/
public String Encrypt(String str,String materialKey)
{
try
{
BASE64Decoder base64d = new BASE64Decoder();
//materialKey = "27jrWz2sxrVbR+pnyg6jWHhgNk4sZo46";
byte[] mykey;
try
{
mykey = base64d.decodeBuffer(materialKey);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

SecureRandom sr = new SecureRandom();
DESedeKeySpec dks = new DESedeKeySpec(mykey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
String EncryptStr = new String((cipher.doFinal(str.getBytes())));
String result = URLEncoder.encode(EncryptStr,"UTF-8");
return result;

}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
ECB ecb = new ECB();
String str = "3033$13311083060$D10$2004-02-24 16:19:27";
String key = "27jrWz2sxrVbR+pnyg6jWHhgNk4sZo46";
String result = ecb.Encrypt(str,key);
System.out.println(result);

}

}

------解决方案--------------------
public class ECB 

/** 

* @param str 要加密的字符串 
* @param materialKey 密钥 
* @return 
*/ 
public String Encrypt(String str,String materialKey) 

try 

BASE64Decoder base64d = new BASE64Decoder(); 
//materialKey = "27jrWz2sxrVbR+pnyg6jWHhgNk4sZo46"; 

byte[] mykey=null;//!!!!!!!!!! 改这里,因为这是局部变量 需要初始化 @@@@@@@@@@@@@@@
try 

mykey = base64d.decodeBuffer(materialKey); 

catch (IOException e) 

// TODO Auto-generated catch block 
e.printStackTrace(); 
return null; 


SecureRandom sr = new SecureRandom(); 
DESedeKeySpec dks = new DESedeKeySpec(mykey); 
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); 
SecretKey securekey = keyFactory.generateSecret(dks); 
Cipher cipher = Cipher.getInstance("DESede"); 
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); 
String EncryptStr = new String((cipher.doFinal(str.getBytes()))); 
String result = URLEncoder.encode(EncryptStr,"UTF-8"); 
return result; 


catch (Exception e) 

// TODO Auto-generated catch block 
e.printStackTrace(); 

return null; 

public static void main(String[] args) 

ECB ecb = new ECB(); 
String str = "3033$13311083060$D10$2004-02-24 16:19:27"; 
String key = "27jrWz2sxrVbR+pnyg6jWHhgNk4sZo46"; 
String result = ecb.Encrypt(str,key); 
System.out.println(result); 



}