从内存中安装的Android应用程序文件生成哈希

时间:2013-11-20 14:05:12

标签: android hash

我能够从示例文件(textFile.txt)生成哈希,该文件是通过我的Android应用程序本身使用以下代码创建的。         现在我想阅读我当前安装的应用程序的已安装的应用程序文件(假设它将是* .apk),从该文件读取字节数组并生成哈希值。

    Is it possible and how to do the same.Any help will be highly appreciated.


String FILENAME ="textFile.txt";
    String strMsgToSave = "content check";
    FileOutputStream fos;
    String outputTxt= "";
    String hash = null;
    String exception=null;
    try
    {
        fos = this.openFileOutput( FILENAME, Context.MODE_PRIVATE );
        fos.write( strMsgToSave.getBytes() );
        fos.close();

        FileInputStream input = openFileInput(FILENAME);
        ByteArrayOutputStream output = new ByteArrayOutputStream ();
        byte [] buffer = new byte [65536];
        int l;
        while ((l = input.read (buffer)) > 0)
            output.write (buffer, 0, l);
        input.close ();
        output.close ();
        byte [] data = output.toByteArray ();
        MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
        byte[] bytes = data;
        digest.update(bytes, 0, bytes.length);
        bytes = digest.digest();
        StringBuilder sb = new StringBuilder();
        for( byte b : bytes )
        {
            sb.append( String.format("%02X", b) );
        }
        hash = sb.toString();
        txtOutput.setText(hash);

    } catch (Exception e) {

        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:0)

我想您可以使用getApplicationContext.getApplicationInfo().sourceDir获取应用程序的apk文件的路径,并使用它实例化一个新文件。 看来你只需要做你想做的事情,你的方法应该有效。

答案 1 :(得分:0)

我已经使用两个不同的Android设备和相同的应用程序实现了以下代码,发现无论设备如何,检索的值都是相同的。以下是相同的代码。所以我想我得到了答案。

        File file=new File(getApplicationContext().getPackageCodePath());  
        FileInputStream input = new FileInputStream(file);
        ByteArrayOutputStream output = new ByteArrayOutputStream ();
        byte [] buffer = new byte [65536];
        int l;
        while ((l = input.read (buffer)) > 0)
               output.write (buffer, 0, l);
        input.close ();
        output.close ();
        byte [] data = output.toByteArray ();
        MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
        byte[] bytes = data;
        digest.update(bytes, 0, bytes.length);
        bytes = digest.digest();
        StringBuilder sb = new StringBuilder();
        for( byte b : bytes )
           sb.append( String.format("%02X", b) );
        hash = sb.toString();

getApplicationContext()。getPackageCodePath()返回此上下文主Android包的完整路径。 Android软件包是一个ZIP文件,其中包含应用程序的主要代码和资产。
如果可以将此视为解决我的问题或提出任何建议,请告诉我。