Skip to content

Instantly share code, notes, and snippets.

@laudarch
Created March 27, 2017 06:28
Show Gist options
  • Save laudarch/5adf1d1e921ad955079ae22fc49a38af to your computer and use it in GitHub Desktop.
Save laudarch/5adf1d1e921ad955079ae22fc49a38af to your computer and use it in GitHub Desktop.
Encryption/Decryption utils for android
package laudarch.utils;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by laudarch on 16/12/13.
*/
public class EncryptionUtils {
public static String sha1(String input) throws NoSuchAlgorithmException {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public static String sha256(String input) throws NoSuchAlgorithmException {
MessageDigest mDigest = MessageDigest.getInstance("SHA256");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
/**
* Verifies SHA1 checksum
* @param data to be verified
* @param testChecksum the expected checksum
* @return true if the SHA1 checksum of data matches the given SHA1 checksum; false otherwise.
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static boolean verifySHA1Checksum(String data, String testChecksum) throws NoSuchAlgorithmException, IOException
{
String dataHash = EncryptionUtils.sha1(data);
return dataHash.equals(testChecksum);
}
/**
* Verifies SHA256 checksum
* @param data to be verified
* @param testChecksum the expected checksum
* @return true if the SHA256 checksum of the data matches the given SHA256 checksum; false otherwise.
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static boolean verifyChecksum(String data, String testChecksum) throws NoSuchAlgorithmException, IOException
{
String dataHash = sha256(data);
return dataHash.equals(testChecksum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment