import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5Bytes { private static byte[] key;//保存MD5算法產生的密鑰 private MD5Bytes() {}//構造方法私有化,即不能用構造方法產生實例 /** * 獲取字符串,用於生成加密後的密鑰 * @param str 被用於加密的字符串 * @return 返回一個本類的實例 * @throws NoSuchAlgorithmException */ public static MD5Bytes getMD5(String str) throws NoSuchAlgorithmException { MD5Bytes md5 = new MD5Bytes(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); key = md.digest(); } catch (NoSuchAlgorithmException e) { throw new NoSuchAlgorithmException("方法:public static MD5Bytes getMD5(String str) " + "throws NoSuchAlgorithmException" + e.getMessage()); } return md5; } /** * 加密單個字節 * @param b * @return 返回被加密後的字節 */ public byte encrptByte(byte b) { for(int i = 0; i < key.length; i++) b = (byte) (b ^ key[i]); return b; } /** * * @param by 字節數組 * @param off 字節數組的起始加密位置(下標) * @param len 字節數組加密字節的個數 * @return 返回加密後的字節 */ public byte[] encrptBytes(byte[] by, int off, int len) { if(len < 0 || len > by.length) len = by.length; if(off < 0 || off > by.length) off = 0; byte[] encrptBy = new byte[len]; for(int i = off; i < by.length && i < off+len; i++) encrptBy[i] = encrptByte(by[i]); return encrptBy; } /** * * @param by 原始字節數組 * @return 返回被加密的數組 */ public byte[] encrptBytes(byte[] by) { return encrptBytes(by,0,by.length); } }