概述
// 向量
private final static String iv = "09876543" ;
// 加解密统一使用的编码方式
private final static String encoding = "utf-8" ;
private static final String ALGORITHM = "3DES"; // 加密算法名
// 生成密钥
private static String getSecretKey() throws Exception {
KeyGenerator keyGenerator = null;
String key="";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timer = sdf.format(new Date());
try {
keyGenerator = KeyGenerator.getInstance(ALGORITHM); // Get the key generator
key=timer+Base64Utils.encode(keyGenerator.generateKey().toString().getBytes()).toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return key; // Generate the secret key
}
/**
* 3DES加密
*
* @param plainText 普通文本
* @return
* @throws Exception
*/
public static String encode(String plainText,String secretKey) throws Exception {
Key deskey = null ;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance( "desede" );
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance( "desede/CBC/PKCS5Padding" );
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte [] encryptData = cipher.doFinal(plainText.getBytes(encoding));
return Base64Utils.encode(encryptData);
}
/**
* 3DES解密
*
* @param encryptText 加密文本
* @return
* @throws Exception
*/
public static String decode(String encryptText,String secretKey) throws Exception {
Key deskey = null ;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance( "desede" );
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance( "desede/CBC/PKCS5Padding" );
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte [] decryptData = cipher.doFinal(Base64Utils.decode(encryptText));
return new String(decryptData, encoding);
}
最后
以上就是英俊橘子为你收集整理的3des加密与解密的全部内容,希望文章能够帮你解决3des加密与解密所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复