Java代码 复制代码 收藏代码
  1. /**
  2. * String Utility Class This is used to encode passwords programmatically
  3. *
  4. * <p>
  5. * <a h ref="StringUtil.java.html"><i>View Source</i></a>
  6. * </p>
  7. *
  8. * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
  9. */
  10. public class PasswordMD5Encryption {
  11. // ~ Static fields/initializers
  12. private static Logger logger = Logger.getLogger(PasswordMD5Encryption.class);
  13. private final static Log log = LogFactory
  14. .getLog(PasswordMD5Encryption.class);
  15.  
  16. // ~ Methods
  17. /**
  18. * Encode a string using algorithm specified in web.xml and return the
  19. * resulting encrypted password. If exception, the plain credentials string
  20. * is returned
  21. *
  22. * @param password
  23. * Password or other credentials to use in authenticating this
  24. * username
  25. * @param algorithm
  26. * Algorithm used to do the digest
  27. *
  28. * @return encypted password based on the algorithm.
  29. */
  30. public static String encodePassword(String password, String algorithm) {
  31. byte[] unencodedPassword = password.getBytes();
  32.  
  33. MessageDigest md = null;
  34.  
  35. try {
  36. // first create an instance, given the provider
  37. md = MessageDigest.getInstance(algorithm);
  38. } catch (Exception e) {
  39. log.error("Exception: " + e);
  40.  
  41. return password;
  42. }
  43.  
  44. md.reset();
  45.  
  46. // call the update method one or more times
  47. // (useful when you don't know the size of your data, eg. stream)
  48. md.update(unencodedPassword);
  49.  
  50. // now calculate the hash
  51. byte[] encodedPassword = md.digest();
  52.  
  53. StringBuffer buf = new StringBuffer();
  54.  
  55. for (int i = 0; i < encodedPassword.length; i++) {
  56. if ((encodedPassword[i] & 0xff) < 0x10) {
  57. buf.append("0");
  58. }
  59.  
  60. buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
  61. }
  62.  
  63. return buf.toString();
  64. }
  65.  
  66. /**
  67. * Encode a string using Base64 encoding. Used when storing passwords as
  68. * cookies.
  69. *
  70. * This is weak encoding in that anyone can use the decodeString routine to
  71. * reverse the encoding.
  72. *
  73. * @param str
  74. * @return String
  75. */
  76. public static String encodeString(String str) {
  77. sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
  78. return encoder.encodeBuffer(str.getBytes()).trim();
  79. }
  80.  
  81. /**
  82. * Decode a string using Base64 encoding.
  83. * @param str
  84. * @return String
  85. */
  86. public static String decodeString(String str) {
  87. sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
  88. try {
  89. return new String(dec.decodeBuffer(str));
  90. } catch (IOException io) {
  91. throw new RuntimeException(io.getMessage(), io.getCause());
  92. }
  93. }
  94.  
  95. public static void main(String[] args) {
  96. String passString = "123456";
  97. String newpass = PasswordMD5Encryption.encodeString(passString);
  98. System.out.println(passString+" 加密后的字符串是 : " + newpass);
  99. String newpassAgin = PasswordMD5Encryption.decodeString(newpass);
  100. System.out.println(newpass+" 加密后再解密的字符串是 : " + newpassAgin);
  101. }
  102. }
/**
 * String Utility Class This is used to encode passwords programmatically
 * 
 * <p>
 * <a h ref="StringUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class PasswordMD5Encryption {
	// ~ Static fields/initializers
	private static Logger logger  = Logger.getLogger(PasswordMD5Encryption.class);
	private final static Log log = LogFactory
			.getLog(PasswordMD5Encryption.class);

	// ~ Methods
	/**
	 * Encode a string using algorithm specified in web.xml and return the
	 * resulting encrypted password. If exception, the plain credentials string
	 * is returned
	 * 
	 * @param password
	 *            Password or other credentials to use in authenticating this
	 *            username
	 * @param algorithm
	 *            Algorithm used to do the digest
	 * 
	 * @return encypted password based on the algorithm.
	 */
	public static String encodePassword(String password, String algorithm) {
		byte[] unencodedPassword = password.getBytes();

		MessageDigest md = null;

		try {
			// first create an instance, given the provider
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			log.error("Exception: " + e);

			return password;
		}

		md.reset();

		// call the update method one or more times
		// (useful when you don't know the size of your data, eg. stream)
		md.update(unencodedPassword);

		// now calculate the hash
		byte[] encodedPassword = md.digest();

		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}

			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * Encode a string using Base64 encoding. Used when storing passwords as
	 * cookies.
	 * 
	 * This is weak encoding in that anyone can use the decodeString routine to
	 * reverse the encoding.
	 * 
	 * @param str
	 * @return String
	 */
	public static String encodeString(String str) {
		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		return encoder.encodeBuffer(str.getBytes()).trim();
	}

	/**
	 * Decode a string using Base64 encoding.
	 * @param str
	 * @return String
	 */
	public static String decodeString(String str) {
		sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
		try {
			return new String(dec.decodeBuffer(str));
		} catch (IOException io) {
			throw new RuntimeException(io.getMessage(), io.getCause());
		}
	}
	
	public static void main(String[] args) {
                String passString = "123456";
		String newpass = PasswordMD5Encryption.encodeString(passString);
		System.out.println(passString+" 加密后的字符串是 : " + newpass);
		String newpassAgin = PasswordMD5Encryption.decodeString(newpass);
		System.out.println(newpass+" 加密后再解密的字符串是 : " + newpassAgin);
	}
}