Skip to content

Instantly share code, notes, and snippets.

@pavi2410
Last active January 28, 2019 19:35
Show Gist options
  • Save pavi2410/41e47f2d351e8a278ba7cc2296dbb034 to your computer and use it in GitHub Desktop.
Save pavi2410/41e47f2d351e8a278ba7cc2296dbb034 to your computer and use it in GitHub Desktop.
Get Keystore SHA1 from a keystore file programmatically in Java
package tk.pavi2410;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
/**
* @author [email protected] (Pavitra)
*/
public class KeyStore {
/**
* Gets the keystore SHA1
*
* @return the keystore SHA1
*/
public String getKeystoreSha1(InputStream keystoreFile) {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(keystoreFile, "android".toCharArray()); // storepass
// Get the chain
Certificate[] chain = ks.getCertificateChain("androidkey"); // alias
// Print the digest of the user cert only
byte[] encCertInfo = chain[0].getEncoded();
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] digest = md.digest(encCertInfo);
return toHexString(digest);
}
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
if (i < len - 1) {
buf.append(":");
}
}
return buf.toString();
}
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment