在使用中發現,通過加密的字符串若是要進行傳輸,須要使用Base64進行編碼,這樣能保證加密信息的完整性,確保未來解密成功。java
import java.security.SecureRandom; import java.util.Base64; import javax.crypto.spec.DESKeySpec; import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKey; import javax.crypto.Cipher; public class DES { /** * 測試方法 */ public static void main(String[] args) { String str = "你好,goldlone"; //密碼最好是8的倍數 String password = "12345678"; String encryStr = DES.encrypt(str, password); System.out.println("加密結果:"+encryStr); String decryStr = DES.decrypt(encryStr, password); System.out.println("解密結果:"+decryStr); } /** * 進行加密操做 * 參數一:待加密的字符串,參數二:加密密鑰 * 返回通過Base64編碼後的字符串 * 編碼格式爲UTF-8 */ public static String encrypt(String encryptionStr, String password) { try{ byte[] encryptionBytes = encryptionStr.getBytes("UTF-8"); SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 建立一個密鑰工廠,而後用它把DESKeySpec轉換成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher對象實際完成加密操做 Cipher cipher = Cipher.getInstance("DES"); // 用密鑰初始化Cipher對象 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); // 執行加密操做 byte[] encryptionBase64Bytes = Base64.getEncoder().encode(cipher.doFinal(encryptionBytes)); // 轉換爲字符串返回 return new String(encryptionBase64Bytes); }catch(Exception e){ e.printStackTrace(); } return null; } /** * 進行解密操做 * 參數一:待解密的字符串,參數二:加密密鑰 * 返回解密後的字符串 */ public static String decrypt(String decryptionBase64Str, String password) { try { byte[] decryptionbytes = Base64.getDecoder().decode(decryptionBase64Str); // DES算法要求有一個可信任的隨機數源 SecureRandom random = new SecureRandom(); // 建立一個DESKeySpec對象 DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 建立一個密鑰工廠 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 將DESKeySpec對象轉換成SecretKey對象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher對象實際完成解密操做 Cipher cipher = Cipher.getInstance("DES"); // 用密鑰初始化Cipher對象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 開始解密操做 return new String(cipher.doFinal(decryptionbytes), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; } }
運行結果:
加密結果:E5t/WSZKkVlr0Uw9cMdddQ==
解密結果:你好,goldlone算法