1.首先书写3DES加密方法,如下:
/**
* 3DES 加密
* @param message 你的密码
* @param password 秘钥
* @return
*/
public static String ThreeDESEconde(String message,String password){
//调用build3DesKey生成秘钥
SecretKey deskey = new SecretKeySpec(build3DesKey(password),"DESede");
try{
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE,deskey);
String outStr = null;
try {
outStr = Base64.encodeBase64String(cipher.doFinal(message.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new String(Base64.encodeBase64(outStr.getBytes()));//返回base64加密
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return "";
}
2.书写生成秘钥的方法:
/**
* 生成秘钥
* @param password 秘钥
* @return
*/
public static byte[] build3DesKey(String password){
byte[] key = new byte[24];//声明一个24位的字节数组,默认里面都是0
byte[] temp;
try{
temp = password.getBytes("UTF-8");//将字符串转成字节数组
if (key.length > temp.length){
//如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中
System.arraycopy(temp,0,key,0,temp.length);
}else {
//如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中
System.arraycopy(temp,0,key,0,key.length);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return key;
}
3.调用示例:
String us = ThreeDESEconde(username,"winning8");
//前面的参数是你的密码,后面的参数是秘钥