3DES加解密程式碼
阿新 • • 發佈:2020-09-11
package com.albedo.security; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import java.security.Key; import java.security.SecureRandom; import java.util.Base64;/** * des 加解密實現 */ public class DES3Util { //字元編碼 public static final String CHARSET_UTF8 = "UTF-8"; //加密演算法DES public static final String DES3 = "desede"; //電話本模式 public static final String DES3_ECB = "DESEDE/ECB/PKCS5Padding"; //加密塊鏈模式--推薦 public static final String DES3_CBC = "DESEDE/CBC/PKCS5Padding";/** * 生成key * * @param password * @return * @throws Exception */ private static Key generateKey(String password) throws Exception { //由於DES3密碼不能小於24位,因此,任意長度密碼經過Md5轉化後,變為定長32位執行加解密處理 DESedeKeySpec dks = new DESedeKeySpec(Md5Utils.encrypt(password).getBytes(CHARSET_UTF8)); SecretKeyFactory keyFactory= SecretKeyFactory.getInstance(DES3); return keyFactory.generateSecret(dks); } /** * 3DES加密字串--ECB格式 * * @param password 加密密碼,長度不能夠小於8位 * @param data 待加密字串 * @return 加密後內容 */ public static String encryptECB(String password, String data) throws Exception{ Key secretKey = generateKey(password); Cipher cipher = Cipher.getInstance(DES3_ECB); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom()); byte[] bytes = cipher.doFinal(data.getBytes(CHARSET_UTF8)); //JDK1.8及以上可直接使用Base64,JDK1.7及以下可以使用BASE64Encoder return new String(Base64.getEncoder().encode(bytes)); } /** * 3DES解密字串--ECB格式 * * @param password 解密密碼,長度不能夠小於8位 * @param data 待解密字串 * @return 解密後內容 */ public static String decryptECB(String password, String data) throws Exception { Key secretKey = generateKey(password); Cipher cipher = Cipher.getInstance(DES3_ECB); cipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom()); return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET_UTF8))), CHARSET_UTF8); } /** * 3DES加密字串-CBC加密格式 * * @param password 加密密碼,長度不能夠小於8位 * @param data 待加密字串 * @return 加密後內容 */ public static String encryptCBC(String password, String data) throws Exception{ Key secretKey = generateKey(password); Cipher cipher = Cipher.getInstance(DES3_CBC); IvParameterSpec spec=new IvParameterSpec("12345678".getBytes(CHARSET_UTF8)); cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec); byte[] bytes = cipher.doFinal(data.getBytes(CHARSET_UTF8)); //JDK1.8及以上可直接使用Base64,JDK1.7及以下可以使用BASE64Encoder return new String(Base64.getEncoder().encode(bytes)); } /** * 3DES解密字串--CBC格式 * * @param password 解密密碼,長度不能夠小於8位 * @param data 待解密字串 * @return 解密後內容 */ public static String decryptCBC(String password, String data) throws Exception { Key secretKey = generateKey(password); Cipher cipher = Cipher.getInstance(DES3_CBC); IvParameterSpec spec=new IvParameterSpec("12345679".getBytes(CHARSET_UTF8)); cipher.init(Cipher.DECRYPT_MODE, secretKey, spec); return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET_UTF8))), CHARSET_UTF8); } }