android md5加密和sha-1加密方法

来源:互联网 发布:淘宝搜索流量下降 编辑:程序博客网 时间:2024/06/07 17:36

网上的确有很多方法,但是正确的确实不好找.幸运的是自己找到了一个

public class MD5 {// MD5加密实例public static String getMD5(String str) throws NoSuchAlgorithmException {MessageDigest md5 = null;try {md5 = MessageDigest.getInstance("MD5");} catch (Exception e) {e.printStackTrace();return "";}char[] charArray = str.toCharArray();byte[] byteArray = new byte[charArray.length];for (int i = 0; i < charArray.length; i++) {byteArray[i] = (byte) charArray[i];}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();}public static String byte2hex(byte[] b) {String hs = "";String stmp = "";for (int n = 0; n < b.length; n++) {stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));if (stmp.length() == 1) {hs = hs + "0" + stmp;} else {hs = hs + stmp;}}return hs;}// SHA1 加密实例public static String encryptToSHA(String info) {byte[] digesta = null;try {// 得到一个SHA-1的消息摘要MessageDigest alga = MessageDigest.getInstance("SHA-1");// 添加要进行计算摘要的信息alga.update(info.getBytes());// 得到该摘要digesta = alga.digest();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}// 将摘要转为字符串String rs = byte2hex(digesta);return rs;}}


原帖地址:http://www.buhaoting.com/chengxu/yundongjianfei/shoushencao/45532.html
顺便给大家提供一个可以验证sha1加密是否正确的网站http://www.bejson.com/ 这个网站还是很不错的,
0 0
原创粉丝点击