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); } }