首页 > 代码库 > Java security MD5加密算法
Java security MD5加密算法
利用java.security对字符串进行MD5加密:
1 import java.security.MessageDigest; 2 import java.security.NoSuchAlgorithmException; 3 4 public class MD5 { 5 public static final String MD5CODE = ""; 6 7 private static MessageDigest messageDigest = null; 8 9 public static String Encode(final String Source) {10 return Encode(Source + MD5CODE, null);11 }12 13 public static String Encode(final String Source, final String charset) {14 if (Source == null)15 return null;16 if (messageDigest == null) {17 try {18 messageDigest = MessageDigest.getInstance("MD5");19 } catch (NoSuchAlgorithmException e) {20 return null;21 }22 }23 if (charset == null || charset.trim().length() <= 0){24 messageDigest.update(Source.getBytes());25 }else {26 try {27 messageDigest.update(Source.getBytes(charset));28 } catch (Exception e) {29 messageDigest.update(Source.getBytes());30 }31 }32 byte[] digesta = messageDigest.digest();33 return Bytes2Hex(digesta);34 }35 36 public static byte[] EncodeBytes(byte[] Source) {37 if (messageDigest == null) {38 try {39 messageDigest = MessageDigest.getInstance("MD5");40 } catch (NoSuchAlgorithmException e) {41 return null;42 }43 }44 messageDigest.update(Source);45 byte[] ret = messageDigest.digest();46 return ret;47 }48 49 public static String Bytes2Hex(final byte[] Source) {50 String hs = "";51 String stmp = "";52 for (int n = 0; n < Source.length; n++) {53 stmp = (java.lang.Integer.toHexString(Source[n] & 0xFF));54 if (stmp.length() == 1)55 hs = hs + "0" + stmp;56 else57 hs = hs + stmp;58 }59 return hs;60 }61 62 public static void main(String args[]) {63 64 String str = "123456";65 String encode = MD5.Encode(str);66 String encode1 = MD5.Encode(str);67 String encode2 = MD5.Encode(str);68 System.out.println("MD5.encode 123456="+encode+"---"+encode1+"---"+encode2);69 70 }71 }
Java security MD5加密算法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。