(转)读取签名信息

import sun.security.pkcs.PKCS7;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;

class SignApk {
        public static X509Certificate readSignatureBlock(InputStream in)
                        throws IOException, GeneralSecurityException {
                PKCS7 pkcs7 = new PKCS7(in);
                return pkcs7.getCertificates()[0];
        }

        public static void main(String[] args) throws FileNotFoundException,
                        IOException, GeneralSecurityException {
                X509Certificate publicKey = readSignatureBlock(new FileInputStream(
                                "D:\cert.rsa"));
                System.out.println("issuer:" + publicKey.getIssuerDN());
                System.out.println("subject:" + publicKey.getSubjectDN());
                System.out.println(publicKey.getPublicKey());
        }
}

输出内容如下:

issuer:CN=Zhang zm
subject:CN=Zhang zm
Sun RSA public key, 1024 bits
modulus: 1543085941444687053482947604843962642184531......

------------------------------------------------------------------------------------------------------------------------------------------------

Android 获取签名、公钥方法

private byte[] getSign(Context context) {

    PackageManager pm = context.getPackageManager();

    List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);

    Iterator<PackageInfo> iter = apps.iterator();

   while (iter.hasNext()) {

         PackageInfo info = iter.next();

         String packageName = info.packageName;

         //按包名 取签名

         if (packageName.equals("com.test.test")) {

            return info.signatures[0].toByteArray();
         }
  }
    return null;
}

 

public static String getPublicKey(byte[] signature) {

        try {

            CertificateFactory certFactory = CertificateFactory

                    .getInstance("X.509");

            X509Certificate cert = (X509Certificate) certFactory

                    .generateCertificate(new ByteArrayInputStream(signature));

            String publickey = cert.getPublicKey().toString();

            publickey = publickey.substring(publickey.indexOf("modulus: ") + 9,

                    publickey.indexOf("\n", publickey.indexOf("modulus:")));

            Log.d("TRACK", publickey);

            return publickey;

        } catch (CertificateException e) {

            e.printStackTrace();

        }

        return null;

}
posted @ 2012-03-15 16:09  S.Kei.Cheung  阅读(769)  评论(0编辑  收藏  举报