说明:
对称加密指加密与解密所使用的密钥为同一个,密钥生成后需要保存起来(一般保存在服务器,使用时从服务器端获取),用于在加密与解密时使用。
DES算法:
algorithm:DES
cipher:DES/ECB/PKCS5Padding
DESede算法(三重DES):
algorithm:DESede
cipher:DESede/ECB/PKCS5Padding
AES算法:
algorithm:AES
cipher:AES/ECB/PKCS5Padding
使用:
public class DESedeUtil {
private static final String algorithm = "AES"; // 可以是DES、DESede(三重DES)、AES
private static final String cipher = "AES/ECB/PKCS5Padding"; // 可以是DES/ECB/PKCS5Padding、DESede/ECB/PKCS5Padding、AES/ECB/PKCS5Padding
public static void main(String[] args) {
String key = generateKey(); // 产生密钥,需要存起来下次使用
System.out.println("密钥为: " + key);
String password = "123456";
String desPwd = encrypt(key, password);
System.out.println("加密后为: " + desPwd);
System.out.println("原密码为: " + decrypt(key, desPwd));
}
/**
* 产生密钥
*/
public static String generateKey() {
try {
SecureRandom sr = new SecureRandom();
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
kg.init(sr);
// 产生密钥对象
SecretKey secretKey = kg.generateKey();
// 对密钥字节数组进行Base64处理
return Base64.encode(secretKey.getEncoded());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* 加密
*
* @param key 密钥
* @param password 明文密码
* @return 返回加密后的密码
*/
public static String encrypt(String key, String password) {
try {
SecretKey deskey = new SecretKeySpec(Base64.decode(key), algorithm);
Cipher c1 = Cipher.getInstance(cipher);
c1.init(Cipher.ENCRYPT_MODE, deskey);
byte[] biff = c1.doFinal(password.getBytes());
return Base64.encode(biff);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
*
* @param key 密钥
* @param password 加密过的密码
* @return 返回解密后的密码
*/
public static String decrypt(String key, String password) {
try {
SecretKey deskey = new SecretKeySpec(Base64.decode(key), algorithm);
Cipher c1 = Cipher.getInstance(cipher);
c1.init(Cipher.DECRYPT_MODE, deskey);
return new String(c1.doFinal(Base64.decode(password)));
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
}