android app开发者如何防止二次打包攻击?

来源:深圳沃龙软件开发公司     2020-10-10

1、新建SignCheck类

/**

 * @创建者 深圳沃龙信息技术有限公司

 * @创建时间 2020-10-10 下午 7:05

 * @描述 新建,用于 校验签名是否正确,防止二次打包

 */

public class SignCheck {

    private Context context;

    private String cer = null;

    private String realCer = null;

    private static final String TAG = "SignCheck";


    public SignCheck(Context context) {

        this.context = context;

        this.cer = getCertificateSHA1Fingerprint();

    }


    public SignCheck(Context context, String realCer) {

        this.context = context;

        this.realCer = realCer;

        this.cer = getCertificateSHA1Fingerprint();

    }


    public String getRealCer() {

        return realCer;

    }


    /**

     * 设置正确的签名

     *

     * @param realCer

     */

    public void setRealCer(String realCer) {

        this.realCer = realCer;

    }


    /**

     * 获取应用的签名

     *

     * @return

     */

    public String getCertificateSHA1Fingerprint() {

        //获取包管理器

        PackageManager pm = context.getPackageManager();


        //获取当前要获取 SHA1 值的包名,也可以用其他的包名,但需要注意,

        //在用其他包名的前提是,此方法传递的参数 Context 应该是对应包的上下文。

        String packageName = context.getPackageName();


        //返回包括在包中的签名信息

        int flags = PackageManager.GET_SIGNATURES;


        PackageInfo packageInfo = null;


        try {

            //获得包的所有内容信息类

            packageInfo = pm.getPackageInfo(packageName, flags);

        } catch (PackageManager.NameNotFoundException e) {

            e.printStackTrace();

        }


        //签名信息

        Signature[] signatures = packageInfo.signatures;

        byte[] cert = signatures[0].toByteArray();


        //将签名转换为字节数组流

        InputStream input = new ByteArrayInputStream(cert);


        //证书工厂类,这个类实现了出厂合格证算法的功能

        CertificateFactory cf = null;


        try {

            cf = CertificateFactory.getInstance("X509");

        } catch (Exception e) {

            e.printStackTrace();

        }


        //X509 证书,X.509 是一种非常通用的证书格式

        X509Certificate c = null;


        try {

            c = (X509Certificate) cf.generateCertificate(input);

        } catch (Exception e) {

            e.printStackTrace();

        }


        String hexString = null;


        try {

            //加密算法的类,这里的参数可以使 MD4,MD5 等加密算法

            MessageDigest md = MessageDigest.getInstance("SHA1");


            //获得公钥

            byte[] publicKey = md.digest(c.getEncoded());


            //字节到十六进制的格式转换

            hexString = byte2HexFormatted(publicKey);


        } catch (NoSuchAlgorithmException e1) {

            e1.printStackTrace();

        } catch (CertificateEncodingException e) {

            e.printStackTrace();

        }

        return hexString;

    }


    //这里是将获取到得编码进行16 进制转换

    private String byte2HexFormatted(byte[] arr) {


        StringBuilder str = new StringBuilder(arr.length * 2);


        for (int i = 0; i <arr.length; i++) {

            String h = Integer.toHexString(arr[i]);

            int l =h.length();

            if (l == 1)

                h = "0" + h;

            if (l > 2)

                h = h.substring(l - 2, l);

            str.append(h.toUpperCase());

            if (i < (arr.length - 1))

                str.append(':');

        }

        return str.toString();

    }


    /**

     * 检测签名是否正确

     * @return true 签名正常 false 签名不正常

     */

    public boolean check() {


        if (this.realCer != null) {

            cer = cer.trim();

            realCer = realCer.trim();

            if (this.cer.equals(this.realCer)) {

                return true;

            }

        }else {

            Log.e(TAG, "未给定真实的签名 SHA-1 值");

        }

        return false;

    }

}

2、在application程序入口,红色部分替换成自己的签名SHA1进行判断(不知道如何获取SHA1信息的,请参考 http://www.wooolong.com/blog/24.html)


 SignCheck signCheck = new SignCheck(this,"40:A0:D4:01:26:79:64:89:B3:E9:0A:CB:EB:21:D7:6D:29:EC:F3:36");

        if(signCheck.check()) {

            //TODO 签名正常

           // ToastUtil.show("签名正常");

        }else {

            //TODO 签名不正确

            ToastUtil.show("该程序存在风险,请前往官方渠道下载正版 app!");

            //延迟两秒跳转

            new Handler().postDelayed(new Runnable() {

                @Override

                public void run() {

                    android.os.Process.killProcess(android.os.Process.myPid());//结束本程序

                    System.exit(0);

                }

            }, 3000);

        }



本内容皆为 深圳沃龙软件开发公司 原创
如需转载,请注明文章出处和来源网址:http://www.wooolong.com/blog/25.html

全部评论

Isobel | 2024-07-16

Wonderful article! We are linking to this great content on our site. Keep up the good writing.

Reply

Velroaenve | 2024-07-16

Проектирование перепланировки — это возможность воплотить ваши мечты о идеальном пространстве. Наша компания предлагает полный комплекс услуг по разработке проекта, включая все необходимые этапы от идеи до реализации. Мы учитываем все технические и эстетические аспекты, чтобы создать гармоничное и функциональное пространство. Обратившись за 《a href=HHtps://potolki-kitstroy.ru/》разработка проекта перепланировки《/a》, вы получите индивидуальный подход и внимательное отношение к деталям. Наши э

Reply

Shantae | 2024-07-16

Hello, i think that i saw you visited my website so i came to “return the favor”.I'm attempting to find things to enhance my website!I suppose its ok to use a few of your ideas!!

Reply

Alberta | 2024-07-17

Купить диплом о среднем специальном: выгодные условия купить диплом о высшем образовании с внесением

Reply

KennethTot | 2024-07-17

《a href=HHtps://spravka-klinica.info/》купить мед справку《/a》

Reply

Gustavonem | 2024-07-17

《a href=HHtps://msk-spravka.info/》купить справку о болезни《/a》

Reply

Rebekah | 2024-07-17

How do you establish your funds for purchasing a home? The worry of a nasty mortgage pressured us to sit down and draw up our first one hundred percent trustworthy and lifelike household price range. If you'll be able to get authorised for a mortgage, it would price you extra in the long term, as lenders who're prepared to overlook unhealthy credit will cost higher interest charges. Can you purchase a house with bad credit? A large down cost will weigh closely in your favor in case your

Reply

Latia | 2024-07-17

Hi! Do you know if they make any plugins to help with Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Kudos!

Reply

KennethTot | 2024-07-17

《a href=HHtps://spravka-klinica.info/》купить мед справку《/a》

Reply

Cleo | 2024-07-17

It's remarkable to pay a quick visit this site and reading the views of all mates regarding this paragraph, while I am also eager of getting experience.

Reply

Carley | 2024-07-17

Thanks for another informative web site. The place else could I am getting that kind of information written in such a perfect means? I've a challenge that I'm just now working on, and I have been on the look out for such information.

Reply

Bernardfou | 2024-07-17

?????? ?????????? ????? ???, ?? ??????????? ???????????? ??? ????? ? ??????? - ??? ????? ???? ???????.

Reply

Karolin | 2024-07-17

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

Reply

发表评论