All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.icymint.libra.jdbc.mask.MessageDigestMask Maven / Gradle / Ivy

package me.icymint.libra.jdbc.mask;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 通用屏蔽结果。
 * 
 * @author Daniel Yu
 * @since 2012-11-2
 * 
 */
public abstract class MessageDigestMask implements Mask {
	private static MessageDigest md = null;
	private static String M = "abcdefabcdef";

	protected MessageDigestMask(String mdname) {
		try {
			md = MessageDigest.getInstance(mdname);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String decode(String encode, String key) {
		return this.rc4(encode, this.digest(key));
	}

	@Override
	public String digest(String str) {
		return this.digest(str, null);
	}

	protected String digest(String str, Charset charset) {
		md.reset();
		String result = "";
		md.update(str.getBytes(charset == null ? Charset.forName("UTF-8")
				: charset));
		byte[] b = md.digest();
		for (int i = 0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
		return result;
	}

	/**
	 * 首字节为字母的信息摘要值。
	 * 
	 * @param str
	 */
	protected String digestLikeName(String str) {
		String res = this.digest(str);
		String a = res.substring(0, 1);
		if (a.matches("\\d")) {
			int i = Integer.parseInt(a);
			res = res.replaceFirst("\\d", M.substring(i, i + 1));
		}
		return res;
	}

	@Override
	public String encode(String source, String key) {
		return this.rc4(source, this.digest(key));
	}

	@Override
	public String mask(String str) {
		return this.digestLikeName(str);
	}

	/**
	 * rc4加密。
	 * 
	 * @param source
	 * @param key
	 */
	protected String rc4(String source, String key) {
		int[] iS = new int[256];
		byte[] iK = new byte[256];

		for (int i = 0; i < 256; i++)
			iS[i] = i;

		int j = 1;

		for (short i = 0; i < 256; i++) {
			iK[i] = (byte) key.charAt((i % key.length()));
		}

		j = 0;

		for (int i = 0; i < 255; i++) {
			j = (j + iS[i] + iK[i]) % 256;
			int temp = iS[i];
			iS[i] = iS[j];
			iS[j] = temp;
		}

		int i = 0;
		j = 0;
		char[] iInputChar = source.toCharArray();
		char[] iOutputChar = new char[iInputChar.length];
		for (short x = 0; x < iInputChar.length; x++) {
			i = (i + 1) % 256;
			j = (j + iS[i]) % 256;
			int temp = iS[i];
			iS[i] = iS[j];
			iS[j] = temp;
			int t = (iS[i] + (iS[j] % 256)) % 256;
			int iY = iS[t];
			char iCY = (char) iY;
			iOutputChar[x] = (char) (iInputChar[x] ^ iCY);
		}

		return new String(iOutputChar);

	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy