package com.cnse.pwdProtected.demo; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Security; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import com.sun.crypto.provider.SunJCE; /** * @author kxw * java des的簡單實現 * @info des生成56爲祕鑰+8爲奇偶校驗位 共64位 *DES算法把64位的明文輸入塊變爲64位的密文輸出塊,它所使用的密鑰也是64位,其算法主要分爲兩步: 1)初始置換 *其功能是把輸入的64位數據塊按位從新組合,並把輸出分爲L0、R0兩部分,每部分各長3 *2位,其置換規則爲將輸入的第58位換到第一位,第50位換到第2位 *依此類推,最後一位是原來的第7位。L0、R0則是換位輸出後的兩部分,L0是輸出的左32位 *R0是右32位,例:設置換前的輸入值爲D1D2D3 *D64,則通過初始置換後的結果爲:L0=D58D50……D8;R0=D57D49……D7。 2)逆置換 *通過16次迭代運算後,獲得L1六、R16,將此做爲輸入,進行逆置換,逆置換正好是初始置換的逆運算,由此即獲得密文輸出。 */ public class DesDemo { // KeyGenerator 提供對稱密鑰生成器的功能,支持各類算法 private KeyGenerator keyGenerator; // SecretKey 負責保存對稱密鑰 private SecretKey secretKey; // Cipher負責完成加密或解密工做 private Cipher cipher; // 該字節數組負責保存加密的結果 private byte[] desStrByte; //構造器初始化 public DesDemo() throws Exception { Security.addProvider(new SunJCE()); // 實例化支持DES算法的密鑰生成器(算法名稱命名需按規定,不然拋出異常) keyGenerator = KeyGenerator.getInstance("DES"); // 生成密鑰 secretKey = keyGenerator.generateKey(); // 生成Cipher對象,指定其支持的DES算法 cipher = Cipher.getInstance("DES"); } /** * main test */ public static void main(String[] args) throws Exception { DesDemo des = new DesDemo(); String msg = "123456"; System.out.println("明文是:" + msg); byte[] encontent = des.desEncoder(msg); byte[] decontent = des.desDecoder(encontent); System.out.println("加密後:" + new String(encontent)); System.out.println("解密後:" + new String(decontent)); } /** * 對字符串加密 */ public byte[] desEncoder(String generalStr) throws Exception { // 根據密鑰,對Cipher對象進行初始化,ENCRYPT_MODE表示加密模式 cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] src = generalStr.getBytes(); // 加密,結果保存進cipherByte desStrByte = cipher.doFinal(src); return desStrByte; } /** * 對字符串解密 */ public byte[] desDecoder(byte[] buff) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // 根據密鑰,對Cipher對象進行初始化,DECRYPT_MODE表示加密模式 cipher.init(Cipher.DECRYPT_MODE, secretKey); desStrByte = cipher.doFinal(buff); return desStrByte; } }