/* ****************************************************************** Copyright 2010 Xu Hui Hui (http://xhh.me) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************** */ package me.xhh.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Logger; /** * Utility for encrypting string in algorithm e.g. "MD5" and "SHA". * @author xhh */ public class Digest { /** use java.util.logging, change to your own if needed */ private static final Logger logger = Logger.getLogger(Digest.class.getName()); /** * Encrypt the input string with MD5 algorithm. * @param input the string to be encrypted * @return the encrypting result */ public static String md5(String input) { String algorithm = "MD5"; try { return digest(input, algorithm); } catch (NoSuchAlgorithmException e) { logger.severe("Invalid algorithm: " + algorithm + ". NoSuchAlgorithmException: " + e.getMessage()); return null; } } /** * Encrypt the input string with SHA algorithm. * @param input the string to be encrypted * @return the encrypting result */ public static String sha(String input) { String algorithm = "SHA"; try { return digest(input, algorithm); } catch (NoSuchAlgorithmException e) { logger.severe("Invalid algorithm: " + algorithm + ". NoSuchAlgorithmException: " + e.getMessage()); return null; } } /** * Encrypt the input string with the given algorithm. * @param input the string to be encrypted * @return the encrypting result */ public static String digest(String input, String algorithm) throws NoSuchAlgorithmException { if (input == null) return null; if (algorithm == null) throw new IllegalArgumentException("Argument algorithm could not be null"); MessageDigest md = null; md = MessageDigest.getInstance(algorithm); md.update(input.getBytes()); byte[] msgDigest = md.digest(); StringBuffer hexStrBuf = new StringBuffer(msgDigest.length); for (byte b : msgDigest) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) hexStrBuf.append('0'); hexStrBuf.append(hex); } return hexStrBuf.toString(); } }