/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

/**
 * @author 田平 2008-5-21 上午10:05:33
 * 
 */
public class PasswordEncoder {

	private static final String coder = "ZX1~CV!3B@N5MA#2S$D4F%G6HJ8K&L0*QW(0E)R_7TYU\\I|OP}qw{ert]yu-i[opa/sd?fg>hjk<lzxcvbnm+Z";

	/**
	 * 加密算法
	 * 
	 * @param plaintext
	 * @return
	 */
	public static String encrypt(String plaintext) {
		if (plaintext == null || "".equals(plaintext)) {
			return "";
		} else {
			StringBuffer result = new StringBuffer();
			int length = plaintext.length();
			for (int i = length - 1; i > -1; i--) {
				char subPlaitext = plaintext.charAt(i);
				int coderLength = coder.length();
				for (int j = 0; j < coderLength; j++) {
					char subCoder = coder.charAt(j);
					if (subPlaitext == subCoder) {
						subPlaitext = coder.charAt(j + 1);
						break;
					}
				}
				result.append(subPlaitext);
			}
			return appendOddEven(result.toString());
		}

	}

	public static String appendOddEven(String resouce) {
		if (resouce == null || "".equals(resouce)) {
			return "";
		} else {
			StringBuffer encrypt = new StringBuffer();
			for (int i = 1; i < resouce.length(); i = i + 2) {
				encrypt.append(resouce.charAt(i)).append(resouce.charAt(i - 1));
			}
			if ((resouce.length() & 1) > 0) {
				encrypt.append(resouce.charAt(resouce.length() - 1));
			}
			return encrypt.toString();
		}
	}

	/**
	 * 解密算法
	 * 
	 * @param ciphertext
	 * @return
	 */
	public static String decrypt(String ciphertext) {
		if (ciphertext == null || "".equals(ciphertext)) {
			return "";
		} else {
			String decrypt = appendOddEven(ciphertext);
			StringBuffer result = new StringBuffer();
			for (int i = decrypt.length() - 1; i > -1; i--) {
				char subDecrypt = decrypt.charAt(i);
				for (int j = 0; j < coder.length(); j++) {
					char subCoder = coder.charAt(j);
					if (subDecrypt == subCoder) {
						subDecrypt = coder.charAt(j - 1);
						break;
					}
				}
				result.append(subDecrypt);
			}
			return result.toString();
		}
	}

	 public static void main(String[] args) {
//		 System.out.println(encrypt("000000"));
//		 System.out.println(decrypt("MHBF~Snn"));
//		 System.out.println(decrypt(encrypt("000000")).equals("000000"));
	 }

}
