md5,base64加密

时间:2024-11-09 17:02:50
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
public class MD5Util {
/***
* MD5加密 生成md5码
* @param 待加密字符串
* @return 返回md5码
*/
public static String md5Encode(String inStr) throws Exception {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
} byte[] byteArray = inStr.getBytes("UTF-8");
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
} /**
* 测试主函数
* @param args
* @throws Exception
*/
public static void main(String args[]) throws Exception {
String appSecret = new String("12345678");
String str = appSecret+WriterOrReaderTxt.readTxt()+appSecret;
String md5=md5Encode(str);
System.out.println("MD5后:" + md5);
System.out.println("Base64后:" +Base64.encodeBase64String(md5.getBytes("UTF-8")));

String result = new String(Base64.encodeBase64(DigestUtils.md5(str.getBytes("UTF-8"))),"UTF-8");
         System.out.println(result);

    }
}