提示:以下是本篇文章正文内容,下面案例可供参考
一、1.字符串的加密
/**
* 加密
**/
private String encryptPassword(String clearText) {
try {
DESKeySpec keySpec = new DESKeySpec(
MyConstant.PASSWORD_ENC_SECRET.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String encrypedPwd = Base64.encodeToString(cipher.doFinal(clearText
.getBytes("UTF-8")), Base64.DEFAULT);
return encrypedPwd;
} catch (Exception e) {
}
return clearText;
}
二、字符串的解密
/**
* 解密
**/
private String decryptPassword(String encryptedPwd) {
try {
DESKeySpec keySpec = new DESKeySpec(MyConstant.PASSWORD_ENC_SECRET.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
byte[] encryptedWithoutB64 = Base64.decode(encryptedPwd, Base64.DEFAULT);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64);
return new String(plainTextPwdBytes);
} catch (Exception e) {
}
return encryptedPwd;
}
三、备注:常量PASSWORD_ENC_SECRET可自行定义。
public class MyConstant {
public static final String PASSWORD_ENC_SECRET = "mythmayor";
}