1. 程式人生 > >解決java的md5與PHP的md5結果不同的問題

解決java的md5與PHP的md5結果不同的問題

/**
     * 獲取MD5加密後的字串
     * @param str 明文
     * @return 加密後的字串
     * @throws Exception 
     */
    public static String getMD5(String str) throws Exception {
        /** 建立MD5加密物件 */
        MessageDigest md5 = MessageDigest.getInstance("MD5"); 
        /** 進行加密 */
        md5.update(str.getBytes());
        /** 獲取加密後的位元組陣列 */
        byte[] md5Bytes = md5.digest();
        String res = "";
        for (int i = 0; i < md5Bytes.length; i++){
            int temp = md5Bytes[i] & 0xFF;
            if (temp <= 0XF){ // 轉化成十六進位制不夠兩位,前面加零
                res += "0";
            }
            res += Integer.toHexString(temp);
        }
        return res;
    }
轉自:https://zhidao.baidu.com/question/680167183405269052.html