天天看點

DES加密、解密字元串算法(java版)

  DESPlus.java package com.des; import java.security.*; import javax.crypto.*; public class DESPlus { private static String strDefaultKey = "national"; private Cipher encryptCipher = null; private Cipher decryptCipher = null; public static String byteArr2HexStr(byte[] arrB) throws Exception { int iLen = arrB.length; // 每個byte用兩個字元才能表示,是以字元串的長度是數組長度的兩倍 StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i 字元串轉換為byte數組, 和public static String byteArr2HexStr(byte[] arrB) * 互為可逆的轉換過程 * * @param strIn * 需要轉換的字元串 * @return 轉換後的byte數組 * @throws Exception * 本方法不處理任何異常,所有異常全部抛出 * @author LiGuoQing */ public static byte[] hexStr2ByteArr(String strIn) throws Exception { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; // 兩個字元表示一個位元組,是以位元組數組長度是字元串長度除以2 byte[] arrOut = new byte[iLen / 2]; for (int i = 0; i 字元串 * * @param strIn * 需加密的字元串 * @return 加密後的字元串 * @throws Exception */ public String encrypt(String strIn) throws Exception { return byteArr2HexStr(encrypt(strIn.getBytes())); } public byte[] decrypt(byte[] arrB) throws Exception { return decryptCipher.doFinal(arrB); } public String decrypt(String strIn) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn))); } private Key getKey(byte[] arrBTmp) throws Exception { // 建立一個空的8位位元組數組(預設值為0) byte[] arrB = new byte[8]; // 将原始位元組數組轉換為8位 for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } // 生成密鑰 Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } } 測試程式 Test.java package com.des; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub try { String test = "Hellow Word!"; //DESPlus des = new DESPlus();//預設密鑰 DESPlus des = new DESPlus("leemenz");//自定義密鑰 System.out.println("加密前的字元:"+test); System.out.println("加密後的字元:"+des.encrypt(test)); System.out.println("解密後的字元:"+des.decrypt(des.encrypt(test))); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }

上一篇: CVS,SVN,Git
下一篇: 關于git和svn