- ProGuard
- ProGuard
- In this document
- See also
- Enabling ProGuard (Gradle Builds)
- Enabling ProGuard (Ant Builds)
- Configuring ProGuard
- Decoding Obfuscated Stack Traces
- Debugging considerations for published applications
- Защита Android приложений от реверс-инжиниринга — ProGuard
- Как включить ProGuard запутывание в Android Studio?
- 3 ответа
- Похожие вопросы:
ProGuard
ProGuard — утилита, которая удаляет из готового кода неиспользуемые фрагменты и изменяет имена переменных и методов для усложнения реверс-инжиниринга приложения. Также позволяет уменьшить размер загружаемых на устройство файлов.
Во время своей работы утилита совершает несколько последовательных шагов.
На первом шаге Proguard рекурсивно определяет, какие классы и члены классов (переменные, методы, константы) используются. Все другие классы или члены классов будут удалены из приложения.
Следующий шаг — оптимизация. Proguard может поменять модификаторы классов и методов, удалить неиспользуемые параметры и т.д. Не всегда подобная оптимизация идёт на пользу, поэтому часто этот шаг пропускают.
Важная часть — обфускация. ProGuard переименовывает классы и члены классов, которые не являются точками входа. Точки входа сохраняют свое оригинальное название. Это затрудняет декомпиляцию и исследование работы приложения (reverse engineering).
В Android не используется, но для обычных приложений Java также используется дополнительный шаг — проверка, что код не может случайно или намеренно вырваться из песочницы виртуальной машины Java. Для того, чтобы эта проверка проходила быстрее, компилятор добавляет к файлам классов дополнительную информацию. Соответственно, ProGuard должен в конце своей работы сформировать новую информацию для этой проверки.
В приложении под Android пользовательский интерфейс чаще всего описывается с помощью XML. Часть классов, использующихся при описании интерфейса, нигде в коде не используется. Поэтому, если не сообщить об этих классах ProGuard, они будут удалены. XML с описаниями интерфейса в процессе сборки анализируются аналогично AndroidManifest.xml, и все перечисленные там классы добавляются в файл конфигурации для ProGuard.
Сформированный файл сохраняется в в app/build/intermediates/proguard-rules/debug/aapt_rules.txt.
Второй файл конфигурации Proguard, который по умолчанию используется при сборке приложения под Android, приходит в составе SDK. Этот файл явно указан в build.gradle нашего приложения.
proguard-android.txt — это дефолтный файл конфигурации, поставляемый с SDK. Экспериментаторы могут заменить его на proguard-android-optimize.txt.
proguard-rules.pro — файл, в который предлагается писать свои директивы для ProGuard. Изначально пустой, находится в каталоге приложения.
Вы можете включить ProGuard не только для release, но и для debug версий. Это очень полезно, потому что поведение приложения с включенным ProGuard может отличаться от приложения с выключенным ProGuard совершенно неожиданным образом. Чем раньше все эти неожиданности будут обнаружены и исправлены, тем лучше. За включение ProGuard отвечает директива minifyEnabled.
Если нет уверенности в правильности работы ProGuard, имеет смысл выключить обфускацию. Для этого добавьте в proguard-rules.pro следующую директиву:
Конфигурации для всех сторонних библиотек, которые вы взяли в android-proguard-snippets, храните в каталоге proguard внутри каталога вашего приложения. Тогда подключить сразу весь каталог можно с помощью следующей директивы в build.gradle:
Очень часто возникают проблемы с ProGuard при подключении сторонних библиотек. Обычно, авторы библиотек прикладывает к описанию необходимые комментарии для решения проблемы.
Источник
ProGuard
In this document
See also
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are Licensing Your Applications.
ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to deal with obfuscated code when you build your application in debug mode. Having ProGuard run is completely optional, but highly recommended.
This document describes how to enable and configure ProGuard as well as use the retrace tool to decode obfuscated stack traces.
Enabling ProGuard (Gradle Builds)
When you create a project in Android Studio or with the Gradle build system, the minifyEnabled property in the build.gradle file enables and disables ProGuard for release builds. The minifyEnabled property is part of the buildTypes release block that controls the settings applied to release builds. Set the minifyEnabled property to true to enable ProGuard, as shown in this example.
The getDefaultProguardFile(‘proguard-android.txt’) method obtains the default ProGuard settings from the Android SDK tools/proguard/ folder. The proguard-android-optimize.txt file is also available in this Android SDK folder with the same rules but with optimizations enabled. ProGuard optimizations perform analysis at the bytecode level, inside and across methods to help make your app smaller and run faster. Android Studio adds the proguard-rules.pro file at the root of the module, so you can also easily add custom ProGuard rules specific to the current module.
You can also add ProGuard files to the getDefaultProguardFile directive for all release builds or as part of the productFlavor settings in the build.gradle file to customize the settings applied to build variants. This example adds the proguard-rules-new.pro to the proguardFiles directive and the other-rules.pro file to the flavor2 product flavor.
Enabling ProGuard (Ant Builds)
When you create an Android project, a proguard.cfg file is automatically generated in the root directory of the project. This file defines how ProGuard optimizes and obfuscates your code, so it is very important that you understand how to customize it for your needs. The default configuration file only covers general cases, so you most likely have to edit it for your own needs. See the following section about Configuring ProGuard for information on customizing the ProGuard configuration file.
To enable ProGuard so that it runs as part of an Ant or Eclipse build, set the proguard.config property in the
/project.properties file. The path can be an absolute path or a path relative to the project’s root.
If you left the proguard.cfg file in its default location (the project’s root directory), you can specify its location like this:
You can also move the the file to anywhere you want, and specify the absolute path to it:
When you build your application in release mode, either by running ant release or by using the Export Wizard in Eclipse, the build system automatically checks to see if the proguard.config property is set. If it is, ProGuard automatically processes the application’s bytecode before packaging everything into an .apk file. Building in debug mode does not invoke ProGuard, because it makes debugging more cumbersome.
ProGuard outputs the following files after it runs:
dump.txt Describes the internal structure of all the class files in the .apk file mapping.txt Lists the mapping between the original and obfuscated class, method, and field names. This file is important when you receive a bug report from a release build, because it translates the obfuscated stack trace back to the original class, method, and member names. See Decoding Obfuscated Stack Traces for more information. seeds.txt Lists the classes and members that are not obfuscated usage.txt Lists the code that was stripped from the .apk
These files are located in the following directories:
/bin/proguard if you are using Ant.
/proguard if you are using Eclipse.
Caution: Every time you run a build in release mode, these files are overwritten with the latest files generated by ProGuard. Save a copy of them each time you release your application in order to de-obfuscate bug reports from your release builds. For more information on why saving these files is important, see Debugging considerations for published applications.
Configuring ProGuard
For some situations, the default configurations in the ProGuard configuration file will suffice. However, many situations are hard for ProGuard to analyze correctly and it might remove code that it thinks is not used, but your application actually needs. Some examples include:
- a class that is referenced only in the AndroidManifest.xml file
- a method called from JNI
- dynamically referenced fields and methods
The default ProGuard configuration file tries to cover general cases, but you might encounter exceptions such as ClassNotFoundException , which happens when ProGuard strips away an entire class that your application calls.
You can fix errors when ProGuard strips away your code by adding a -keep line in the ProGuard configuration file. For example:
There are many options and considerations when using the -keep option, so it is highly recommended that you read the ProGuard Manual for more information about customizing your configuration file. The Overview of Keep options and Examples sections are particularly helpful. The Troubleshooting section of the ProGuard Manual outlines other common problems you might encounter when your code gets stripped away.
Decoding Obfuscated Stack Traces
When your obfuscated code outputs a stack trace, the method names are obfuscated, which makes debugging hard, if not impossible. Fortunately, whenever ProGuard runs, it outputs a mapping.txt file, which shows you the original class, method, and field names mapped to their obfuscated names.
The retrace.bat script on Windows or the retrace.sh script on Linux or Mac OS X can convert an obfuscated stack trace to a readable one. It is located in the /tools/proguard/ directory. The syntax for executing the retrace tool is:
If you do not specify a value for , the retrace tool reads from standard input.
Debugging considerations for published applications
Save the mapping.txt file for every release that you publish to your users. By retaining a copy of the mapping.txt file for each release build, you ensure that you can debug a problem if a user encounters a bug and submits an obfuscated stack trace. A project’s mapping.txt file is overwritten every time you do a release build, so you must be careful about saving the versions that you need. For Eclipse, this file is stored in
/bin/proguard/ . For Android Studio, this file is stored in the app build/outs/ folder.
Источник
Защита Android приложений от реверс-инжиниринга — ProGuard
ProGuard — это утилита для сокращения, оптимизации и обфускации кода. На выходе вы получаете *.apk меньшего размера, который намного сложнее реинжинирить. На developer.android.com написано, что ProGuard внедрен в систему сборки Android приложений. Однако, я заметил, что эта утилита появилась в моей папке с SDK только после обновления до r9.
ProGuard запускается только когда вы запускаете сборку в «release» режиме. Для тех, кто не знает как это сделать (в Eclipse): правой кнопкой нужно вызвать контекстное меню проекта, затем Export -> Android -> Export Android Application. Конфиг-файл появляется автоматически, при создании проекта, в его корне, под именем proguard.cfg. Если у вас он не появился, проверьте наличие утилитки в папке с вашим SDK.
Далее, чтобы включить сам обфускатор перед сборкой, нужно добавить в файл /root_of_your_project/default.properties строку вида proguard.config=/path/proguard.cfg, где path — путь к файлу. Таким образом можно таскать один конфиг для кучи проектов.
Итак, после «release» сборки ProGuard немножко намусорит в одной из следующих папок:
- /root_of_your_project/proguard — при использовании Eclipse
- /root_of_your_project/bin/proguard — при использовании Ant
Создаются файлы:
- dump.txt — описывает внутренности всех класс-файлов в вашем *.apk
- mapping.txt — представляет отображение между исходными и обфусцированными классами, полями классов, методами.
- seeds.txt — список необфусцированных классов
- usage.txt — код, вытащенный из *.apk
Также на developer.android.com предупреждают о том, что при обработке кода ProGuard’ом могут возникнуть осложнения в виде ClassNotFoundException. Чтобы избежать подобного, можно добавить строку в конфиг:
Подробнее о настройке конфига можно почитать здесь. Собственно, там же можно найти пару сэмплов.
Кроме этого, в папке /path_to_your_SDK/tools/proguard/bin лежит некий скрипт под названием retrace.bat (для Linux/Mac OS X — retrace.sh). Он позволяет преобразовать обфусцированное в читаемое, используя вышеозначенный mapping.txt.
Синтаксис использования:
Также скрипт воспринимает стандартный ручной ввод текста, в случае если вам лень писать путь к .
Если у вас при первом же запуске в «release» режиме с ProGuard’ом (с дефолтными настройками) вылетает ошибка с кодом 1, то скорее всего в пути к вашему SDK есть пробелы — удалите их, и все заработает.
Источник
Как включить ProGuard запутывание в Android Studio?
Я должен защитить свое приложение, включив обфускацию Proguard в Android Studio. Я искал процесс его применения, но не получил никакого четкого решения. Когда я пытаюсь это сделать, я всегда получаю ошибку. Итак, может ли кто-нибудь сказать мне четкие шаги, чтобы применить его в моем приложении?
Я делаю это следующими шагами:
В Android Studio откройте проект Android.
Перейдите в режим Просмотра проекта.
Измените следующую строку:
minifyEnable false — minifyEnable true
Установить ProGuard правил(необязательно)
4.1 В представлении проекта выберите файл proguard-rules.pro.
4.2 Добавьте в следующие строки, чтобы сказать ProGuard не запутывать определенные классы.
Ошибка, которую я получаю, следуя следующим шагам
Error:Execution не удалось выполнить задачу ‘:app:packageRelease’. Не удалось вычислить hash из D:\Android\Pojectname\app\build\intermediates\classes-proguard\release\classes.jar
3 ответа
Гугл намекает, что разработчики, возможно, захотите, чтобы скрыть байт-код: http://android-developers.blogspot.com/2010/09/программы ProGuard-android-и-лицензирование-server.html Я последовал инструкциям Google, чтобы получить запутанное приложение Android, которое, на первый взгляд, казалось.
Поскольку мы можем настроить параметры Proguard в progaurd.cfg, есть ли способ настроить его в Android Studio? И если да, то как?
Чтобы включить ProGuard в Android Studio.
Ниже приведен пример того, как включить ProGuard по умолчанию в Android Studio.
- Перейдите к файлу build.gradle приложения
- включите minifyEnabled true
- включите shrinkResources true , чтобы уменьшить размер APK
proguardFiles getDefaultProguardFile(‘proguard-android.txt’) , чтобы включить значение по умолчанию. Если вы хотите использовать свой собственный файл proguard, используйте следующие правила.
Ссылка с настройками ProGuard для Android и другие настройки доступны в этих ссылках:
Для получения более подробной информации перейдите по этой ссылке
Я разобрался в проблеме:
Откройте proguard-rules.pro для вашего проекта и добавьте это в нижнюю часть:
В основном, как я решил это, я попытался запустить свое приложение в режиме ‘release’ и получил кучу ошибок, подобных этому парню здесь: https://github.com/square/okio/issues/144
Я в значительной степени следил за тем, что он сказал, и исправил это.
Надеюсь, это поможет другим с созданием их APK!
посетите более подробную информацию здесь :
если вы создаете проект android с помощью jack, то он автоматически выполнит сжатие, запутывание, переупаковку и многодекс. Просто добавьте ниже в :
и в типах сборки укажите файл project proguard :
Чтобы отключить обфускацию ProGuard, необходимо добавить строку ниже в файл proguard-project.txt
Всем привет, Я знаю, что вопросы о proguard уже заданы и на них даны ответы. Я прохожу по некоторым ссылкам. Я использую Eclipse juno и ADT 19. Вот мой sdk Что я хочу, так это чтобы кто-нибудь дал мне полную информацию о том.
Я новичок в Android и Android Studio. Во время обучения я наткнулся на сервисы Google Play для рекламы и все такое. Я попытался включить proguard в своем проекте, но прочитал приведенную ниже ссылку proguard . Проблема в том, что я не могу найти proguard-project.txt или proguard.cfg в структуре.
Похожие вопросы:
У меня есть более старая версия android studio, и я счастлив от этого. Я думаю, что в более новой версии android studio, proguard также был обновлен. Теперь я хочу иметь обновленную версию proguard.
Я пытаюсь создать приложение android, используя scala и android studio. Компиляция не должны быть исключением: Error:java.lang.ArrayIndexOutOfBoundsException: 4 at.
IDE : Android Studio 1.1.0 Тема : ProGuard Проблема : ProGuard файлов или инструментов, не распознанных Android Studio, getDefaultProguardFile не могут быть решены , и в приложении нет.
Гугл намекает, что разработчики, возможно, захотите, чтобы скрыть байт-код: http://android-developers.blogspot.com/2010/09/программы ProGuard-android-и-лицензирование-server.html Я последовал.
Поскольку мы можем настроить параметры Proguard в progaurd.cfg, есть ли способ настроить его в Android Studio? И если да, то как?
Всем привет, Я знаю, что вопросы о proguard уже заданы и на них даны ответы. Я прохожу по некоторым ссылкам. Я использую Eclipse juno и ADT 19. Вот мой sdk
Источник