Android 檔案SHA-MD5校驗工具類
摘要:import android.util.Log;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchA...
import android.util.Log; import java.io.FileInputStream; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 加密工具類 * author:wiki on 2018/12/12 * email:[email protected] */ public class SHAUtil { public static final String TAG = SHAUtil.class.getSimpleName(); /** * 傳入文字內容,返回 SHA-256 串 * * @param strText * @return */ public static String getTextSHA256(final String strText) { return SHA(strText, "SHA-256"); } /** * 傳入文字內容,返回 SHA-512 串 * * @param strText * @return */ public static String getTextSHA512(final String strText) { return SHA(strText, "SHA-512"); } /** * 字串 SHA 加密 * * @param strText * @return */ private static String SHA(final String strText, final String strType) { // 返回值 String strResult = null; // 是否是有效字串 if (strText != null && strText.length() > 0) { try { // SHA 加密開始 // 建立加密物件 並傳入加密型別 MessageDigest messageDigest = MessageDigest.getInstance(strType); // 傳入要加密的字串 messageDigest.update(strText.getBytes()); // 得到 byte 型別結果 byte byteBuffer[] = messageDigest.digest(); // 將 byte 轉換為 string StringBuffer strHexString = new StringBuffer(); // 遍歷 byte buffer for (int i = 0; i < byteBuffer.length; i++) { String hex = Integer.toHexString(0xff & byteBuffer[i]); if (hex.length() == 1) { strHexString.append('0'); } strHexString.append(hex); } // 得到返回結果 strResult = strHexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return strResult; } /** * 校驗 * @param filename 檔名 * @param strType校驗型別--SHA-1,SHA-256,SHA-384,SHA-512,MD5,MD2 * @returnbyte[] * @throws Exception */ private static byte[] createChecksum(String filename, String strType) throws Exception { InputStream fis = new FileInputStream(filename);//將流型別字串轉換為String型別字串 byte[] buffer = new byte[1024]; MessageDigest complete = MessageDigest.getInstance(strType); int numRead; do { numRead = fis.read(buffer);//從檔案讀到buffer,最多裝滿buffer if (numRead > 0) { complete.update(buffer, 0, numRead);//用讀到的位元組進行strType的計算,第二個引數是偏移量 } } while (numRead != -1); fis.close(); return complete.digest(); } public static String getMD5Checksum(String filename) throws Exception { byte[] b = createChecksum(filename, "MD5"); return byte2String(b); } public static String getSHA256Checksum(String filename) throws Exception { byte[] b = createChecksum(filename, "SHA-256"); return byte2String(b); } public static String getSHA512Checksum(String filename) throws Exception { byte[] b = createChecksum(filename, "SHA-512"); return byte2String(b); } private static String byte2String(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte b : bytes) { //加0x100是因為有的b[i]的十六進位制只有1位 result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); } Log.i(TAG, "checkSum: " + result.toString()); return result.toString(); } }