Created
March 4, 2019 03:12
-
-
Save wuyisheng/cbe922a3881709a1ae74913a0e8b9422 to your computer and use it in GitHub Desktop.
simple util for sha1 check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.yeshen.utils; | |
import android.support.annotation.WorkerThread; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.InputStream; | |
import java.security.MessageDigest; | |
/********************************************************************* | |
* This file is part of Download project | |
* Created by hello@yeshen.org on 17-1-16. | |
* Copyright (c) 2016 yeshen, org. - All Rights Reserved | |
*********************************************************************/ | |
public class Sha1 { | |
@WorkerThread | |
public static boolean checkSha1(String sha1, File file) { | |
if (TextUtils.isEmpty(sha1) || file == null || !file.isFile() || !file.exists()) | |
return false; | |
InputStream is = null; | |
try { | |
MessageDigest digest = MessageDigest.getInstance("SHA-1"); | |
is = new FileInputStream(file); | |
int n = 0; | |
byte[] buffer = new byte[8192]; | |
while (n != -1) { | |
n = is.read(buffer); | |
if (n > 0) { | |
digest.update(buffer, 0, n); | |
} | |
} | |
byte digestBytes[] = digest.digest(); | |
StringBuilder hexString = new StringBuilder(); | |
for (byte aMessageDigest : digestBytes) { | |
String shaHex = Integer.toHexString(aMessageDigest & 0xFF); | |
if (shaHex.length() < 2) { | |
hexString.append(0); | |
} | |
hexString.append(shaHex); | |
} | |
return sha1.equalsIgnoreCase(hexString.toString()); | |
} catch (IOException | NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} finally { | |
if (is != null) try { | |
is.close(); | |
} catch (IOException e) {/*ignore*/} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment