0

I am a newbie with Security in Android .. I am trying to get the sha1 of the signing certificate fingerprint of the android app , I wanna get the same result of the cmd : keytool -v -list -keystore " PATH of key " -alias "alias of the key" -storpass " password" I tried this code but it gave me a different result

    android.content.pm.Signature[] sigs;
        try {
            sigs = this.getPackageManager().getPackageInfo(this.getPackageName(),
                    PackageManager.GET_SIGNATURES).signatures;

            byte[] cert = sigs[0].toByteArray();
                 InputStream input

 = new ByteArrayInputStream(cert);
             CertificateFactory cf = null;
        try {
                cf = CertificateFactory.getInstance("X509");


            } catch (CertificateException e) {
                    e.printStackTrace();
            }
            X509Certificate c = null;

            try {

                    c = (X509Certificate) cf.generateCertificate(input);
                    Signature signature=null;
    signature = Signature.getInstance("SHA1withRSA");
                         signature.initVerify(c.getPublicKey());
                            signature.update(cert);
                           System.out.println("signature"+ signature.sign());
Ghitay
  • 3
  • 5

1 Answers1

5

My SignatureUtils class uses SHA-256 (available via the Java 7 keytool), and the values line up. Hence, this method should give you the SHA-1 signature hash:

  public static String getSignatureHash(Context ctxt, String packageName)
                                                                         throws NameNotFoundException,
                                                                         NoSuchAlgorithmException {
    MessageDigest md=MessageDigest.getInstance("SHA-1");
    Signature sig=
        ctxt.getPackageManager()
            .getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures[0];

    return(toHexStringWithColons(md.digest(sig.toByteArray())));
  }

where toHexStringWithColons() is based off of this StackOverflow answer:

  public static String toHexStringWithColons(byte[] bytes) {
    char[] hexArray=
        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F' };
    char[] hexChars=new char[(bytes.length * 3) - 1];
    int v;

    for (int j=0; j < bytes.length; j++) {
      v=bytes[j] & 0xFF;
      hexChars[j * 3]=hexArray[v / 16];
      hexChars[j * 3 + 1]=hexArray[v % 16];

      if (j < bytes.length - 1) {
        hexChars[j * 3 + 2]=':';
      }
    }

    return new String(hexChars);
  }

Since SHA-1 is not a great hash algorithm anymore, and since you can get SHA-256 from keytool, you might consider just using my CWAC-Security library and SignatureUtils directly.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491