DES加密解密(JAVA)

今天在網上搜了一下DES加密算法(註釋部分展開),總報如下錯誤:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

最終原因是byte數組是不能強制轉換成字符串的,換言之:字符串(2個字節)和byte數組在這種情況下不是互逆的;要避免這種情況,我們需要做一些修訂,可以考慮將二進制數據轉換成十六進制表示

在網上找了些代碼,修改以後如下:

 

public class DES {
 private Key key;        //密鑰
 /**
     * 根據參數生成KEY
     *
     * @param strKey 密鑰字符串
     */
    public void getKey(String strKey) {
        try {
            KeyGenerator _generator = KeyGenerator.getInstance("DES");
            _generator.init(new SecureRandom(strKey.getBytes()));
            this.key = _generator.generateKey();
            _generator = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 加密String明文輸入,String密文輸出
     *
     * @param strMing String明文
     * @return String密文
     */
    public String getEncString(String strMing) {
        byte[] byteMi = null;
        byte[] byteMing = null;
        String strMi = "";
        try {
            /*byteMing = strMing.getBytes("UTF8");
            byteMi = this.getEncCode(byteMing);
            strMi = new String(byteMi, "UTF8");*/
         strMi = parseByte2HexStr(getEncCode(strMing.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            byteMing = null;
            byteMi = null;
        }
        return strMi;
    }
    /**
     * 解密 以String密文輸入,String明文輸出
     *
     * @param strMi String密文
     * @return String明文
     */
    public String getDesString(String strMi) {
     byte[] byteMi = null;
        byte[] byteMing = null;
        String strMing = "";
        try {
         /*byteMi = strMi.getBytes("UTF8");
            byteMing = this.getDesCode(byteMi);
            strMing = new String(byteMing, "UTF8");*/
         strMing = new String(getDesCode(parseHexStr2Byte(strMi)));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            byteMing = null;
            byteMi = null;
        }
        return strMing;
    }
    /**
     * 加密以byte[]明文輸入,byte[]密文輸出
     *
     * @param byteS byte[]明文
     * @return byte[]密文
     */
    private  byte[] getEncCode(byte[] byteS) {
        byte[] byteFina = null;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byteFina = cipher.doFinal(byteS);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }
    /**
     * 解密以byte[]密文輸入,以byte[]明文輸出
     *
     * @param byteD byte[]密文
     * @return byte[]明文
     */
    private  byte[] getDesCode(byte[] byteD) {
        Cipher cipher;
        byte[] byteFina = null;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byteFina = cipher.doFinal(byteD);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }
   
    /**
     * 將二進制轉換成16進制
     * @param buf
     * @return
     */
     public  String parseByte2HexStr(byte buf[]) { 
      StringBuffer sb = new StringBuffer(); 
   for (int i = 0; i < buf.length; i++) {
    String hex = Integer.toHexString(buf[i] & 0xFF);
    if (hex.length() == 1) {
     hex = '0' + hex;
    }
    sb.append(hex.toUpperCase());
   }
   return sb.toString();
     }
      
     /**
      * 將16進制轉換爲二進制
      * @param hexStr
      * @return
      */
  public byte[] parseHexStr2Byte(String hexStr) {
 
   if (hexStr.length() < 1)
 
    return null;
   byte[] result = new byte[hexStr.length() / 2];
   for (int i = 0; i < hexStr.length() / 2; i++) {
    int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
    int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
      16);
    result[i] = (byte) (high * 16 + low);
   }
   return result;
  }

 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  DES encrypt = new DES();  
  encrypt.getKey("嘿嘿");  
  String strEnc = encrypt.getEncString("hi,我是程序員");
  System.out.println(strEnc);
  String strDes = encrypt.getDesString(strEnc);
  System.out.println(strDes);
 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章