原創:[email protected] ,歡迎喜歡Java的網友加我
DES加密封裝
package org.jtool.desutils;import java.security.SecureRandom;import javax.crypto.*;import Javax.crypto.spec.DESKeySpec;public class DESEncrypt { private byte[] desKey; public DESEncrypt(byte[] desKey) { this.desKey = desKey; } public byte[] doEncrypt(byte[] plainText) throws Exception { // DES算法要求有一個可信任的隨機數源 SecureRandom sr = new SecureRandom(); byte rawKeyData[] = desKey;/* 用某種方法獲得密匙數據 */ // 從原始密匙數據創建DESKeySpec對象 DESKeySpec dks = new DESKeySpec(rawKeyData); // 創建一個密匙工廠,然後用它把DESKeySpec轉換成 // 一個SecretKey對象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); // Cipher對象實際完成加密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher對象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 現在,獲取數據並加密 byte data[] = plainText;/* 用某種方法獲取數據 */ // 正式執行加密操作 byte encryptedData[] = cipher.doFinal(data); return encryptedData; }}
DES解密封裝
package org.jtool.desutils;import java.security.SecureRandom;import javax.crypto.*;import Javax.crypto.spec.DESKeySpec;public class DESDecrypt { private byte[] desKey; public DESDecrypt(byte[] desKey) { this.desKey = desKey; } public byte[] doDecrypt(byte[] encryptText) throws Exception { // DES算法要求有一個可信任的隨機數源 SecureRandom sr = new SecureRandom(); byte rawKeyData[] = desKey; /* 用某種方法獲取原始密匙數據 */ // 從原始密匙數據創建一個DESKeySpec對象 DESKeySpec dks = new DESKeySpec(rawKeyData); // 創建一個密匙工廠,然後用它把DESKeySpec對象轉換成 // 一個SecretKey對象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); // Cipher對象實際完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher對象 cipher.init(Cipher.DECRYPT_MODE, key, sr); // 現在,獲取數據並解密 byte encryptedData[] = encryptText;/* 獲得經過加密的數據 */ // 正式執行解密操作 byte decryptedData[] = cipher.doFinal(encryptedData); return decryptedData; }}
DES加解密使用樣例
package org.jtool.desutils;/** * */public class DESTest { public static void main(String[] args) throws Exception { String key = "ABCDEFGH"; String value = "AABBCCDDEE"; DESEncrypt desEncrypt = new DESEncrypt(key.getBytes()); byte[] encryptText = desEncrypt.doEncrypt(value.getBytes()); System.out.println("doEncrypt - " + toHexString(encryptText)); System.out.println("doEncrypt - " + new String(encryptText)); DESDecrypt desDecrypt = new DESDecrypt(key.getBytes()); byte[] decryptText = desDecrypt.doDecrypt(encryptText); System.out.println("doDecrypt - " + new String(decryptText)); System.out.println("doDecrypt - " + toHexString(decryptText)); } /** * 16進制顯示數據 * * @param value 字節數組 * @return */ public static String toHexString(byte[] value) { String newString = ""; for (int i = 0; i < value.length; i++) { byte b = value[i]; String str = Integer.toHexString(b); if (str.length() > 2) { str = str.substring(str.length() - 2); } if (str.length() < 2) { str = "0" + str; } newString += str; } return newString.toUpperCase(); }}