How to Hide & Protect API Keys in Your Android App (Reverse Engineering)
HTML-код
- Опубликовано: 26 ноя 2024
- To make sure only you can access your app's API keys, you need to follow some guidelines. In this video I'll show you what these are.
⭐ Get certificates for your future job
⭐ Save countless hours of time
⭐ 100% money back guarantee for 30 days
⭐ Become a professional Android developer now:
pl-coding.com/...
💻 Let me personally review your code and provide individual feedback, so it won't backfire and cost you a fortune in future:
elopage.com/s/...
🎓 Become an industry-ready developer in the Mobile Dev Campus:
pl-coding.com/...
🎁 Get my FREE 4.5h course "The Best Practice Guide to Android Architecture":
pl-coding.com/...
Read our weekly Android blog:
pl-coding.com/...
Join this channel to get access to perks:
/ @philipplackner
Join my Discord server:
/ discord
Regular programming advice on my Instagram page: / _philipplackner_
Checkout my GitHub: github.com/phi...
You like my free content? Here you can buy me a coffee:
www.buymeacoff...
Nice video, but when decompiling the apk you can still get those values from the BuildConfig file
We can also Android NDK enviornment where we use c or c++ files, which are directly compiled to binary code. That is the best way to keep any confidential data on client side..
like you want to write to file using C++, how is this even different from java? or maybe you think that hardcoding C++ value and providing interface for java is something really hard? Open that binary file with text editor and you will find your key in 5 seconds
why using the api key directly in the code? you can just send a request to your own server that handles the api key and asks the api
Because lots of APIs don't work that way. For example the Google maps sdk for Android expects the key to be merged into the manifest. Also you still need to protect the server then, since what would keep an attacker back from making the same request?
Just keep appending new videos like this one to your android security playlist.
hey buddy please update this video as kotlin is introduced as buildgradle lang and it's not working thhere
Thank you soo much for this as I was actually looking for something like this like yesterday and see it come from you is really satisfying :))
Thanks for sharing, It is a common interview question...
Thanks for considering my comment and making the video
Thank you very much Philipp. I have struggled a lot with this issue. Now "we" solved it :P
Hey Mate,
Protecting Api keys from server is better option that this since generated build config file will expose all the keys.
One more option we have is using CMake
The "buildConfigField" causes an error with newer versions of Gradle and Android Studio: "Build Type contains custom BuildConfig fields, but the feature is disabled". You can fix this by adding
android {
...
buildFeatures {
...
buildConfig = true
}
}
Just ran into this myself. To be clear for others, that code goes in the App level build.gradle file, listed in Android Studio Giraffe as build.gradle( :app)
I did a research on protecting the API key.
with how on results you are very good. However, when the hacker gets your APK file, they will easily decompile the encrypted and get the API key easily.
Currently, I find the best solution is to save the API key in a native C++ class or create a secure server that provides the API key
Option 1 can still be decompiled. Any api key can be found if someone really wants it
Thanks bro, much love❤
Love back!
What you know I have done !! . The scarry part is that how easy is that !!! .Mailed to the concerned person.
hey people does anyone know which import goes into 4:08? Properties properties = new Properties() thnx
I get
Properties properties = new Properties()
1st Properties has error Classifier 'Properties' does not have a companion object, and thus must be initialized here
equal sign has red underline
new Properties() - Properties ()
Properties properties = new Properties()
properties.load(project.rootProject.file("local.properties").newDataInputStream())
buildConfigField("String", "ARC_API_KEY", "\"${properties.getProperty("ARCMAP_API_KEY")}\""
load is red -Unresolved reference: load
newDataInputStream() - Unresolved reference: newDataInputStream
properties.getProperty - getProperty is red underline
I am so lost it is not even funny ... thanx!
hey did you solved the error
//protect api key
val properties=Properties()
properties.load(project.rootProject.file("local.properties").inputStream())
buildConfigField ("String","API_KEY","\"${properties.getProperty("API_KEY")}\"")
buildFeatures{
viewBinding=true
buildConfig = true
}
//hope the error got resolved
Hi, How do we use this in manifest file?
One Addition, I think you stated it already in some comments this will just make it harder one that does want to find the key will find it for sure. However, even without decompiling an attacker will in first place just try to use a proxy e.g. Charles proxy maybe and check the requests if you do not use certificate pinning. I like your content but people may take it for the bulletproof solution because they may not listen carefully. And yes for 3rd party Apis its cool if you can have the key on your servers and enforce user authentication as well so no one unwanted may talk to your API 👍
I think I stressed out multiple times that keeping an api key in the app is not 100% safe 🤔
@@PhilippLackner keeping your API keys on the server requires you to have some kind of jwt token to be obtained and stored locally. Isn't that an issue storing it in sharedPrefs, protoStore, sqlite? (Even using encrypted storage)
You still have to store say sqlcipher password somewhere in your compiled app in order to encrypt and decrypt sqlite database. And decompiled app will show this password.
Maybe we can obtain jwt+sqlcipher pass on login session and store sclcipher password in encrypted sharedprefs to read/write encrypted sql? As far as I know encrypted sharedPrefs store its keys in OS protected storage
It amazes me that Google has not yet implemented an encrypted storage standard into Android Studio. This issue shouldn't be an us problem if we're using Android Studio to build apps for Google's ecosystem.
Additionally one could via smalli, painstakingly attempt to log every variable, function parameters, and return value (similar to strace), and thus attempt to locate api-key-like values by inspecting the output
Hi Phillip you can make updated version of this video with google security plugin
It's okay to use the application signature as an additional key and check it on the server side to ensure that the request is coming from my application
Exactly
What stops an attacker to just send the right signature from a modified version of your app? You can't trust the client.
Can you tell me more about this approach please?
I would want to hear that approach too
If you use a application signature you can reuse that in a replay attack (sending the same signature from an attacker app).
Thanks!😍
Api key shouldn't be used as authentication anyway. They are for authorisation. You should still be authenticated otherwise like oauth and perhaps retrieve the key from server dynamically.
How should this be a difference? Technically it’s the same problem
Great one, I do it in this way too, except I create my own properties file for that api key.
I hide my key in native c code as it contains garbage value and it's hard to access key from it. And I just don't put my key as it is... I always break the key in may parts and add some more symbols in it to make it harder after try to extract it from reverse engineered extracted APK...
What about in the case of SSL Pinning. How do you safe secure your certificate public key on the app since the app needs it to authenticate the data
Hey Phillip, I've been using this approach for saving the API keys, but in a modular architecture is there a way to pass these values to the specific module (let's say in layered modular architecture in where you set your network config in one of the layers).
Did you solve this issue. I have same question
@@Koki-hq1yc unfortunately I couldn’t find any solution yet
Thanks a lot Phillip ❤️💯💯
good one Phillippuh , make a video series for API integration in android
Thanks for the video, I have two doubts about how we will handle The project is in CICD and when we are working as a team. in both cases we are not sharing the git ignore
You can set your keys as environment variables and include them in (almost) the same way as is shown in this video. That keeps them out of source control, works with local builds, but also allows you to set environment variables as configuration options in your CICD solution.
it will be good to add more videos about that topic
What is still unclear?
@@PhilippLackner everything is clear for me, I mean more tips about security as you mentioned at the end of the video
i love the explication, one fan more :)
Hello Philipp L. Many thanks for the explanation. Excellent as always. Could you do video explaining how to load data from local JSON file? many thanks
Thank you so much for this, but please how do I protect my web app,
Like a WordPress website that I converted into an android app
Is it protected as my website is protected?
Please help me out, let me know, if I will need to protect the we app separately
God bless you
yo bro, really thankya. Big respect
Can you make a video about certificate pinning?
Nice video! But made me think about CI, if i'm trying to use github actions and try to run a gradle action such as lintDebug, how would i do that if in the repository doesn't have the api_key explicitly
Hi it was me who gave the firebase suggestion on stack over flow. Too Sad that it is still the only way .
thanks a lot. Could we save some secret keys in jenkins and got the value from app? if could , could you please help share it, thanks a lot
An even easier way of accessing local.properties is: val localProperties = gradleLocalProperties(rootDir) - then you can use localProperties["someKey"] to access its value.
Ty for wasting my time, its not even working.
@@and70 you’re welcome.
you don't know how long i waited for this video tutorial
is it possible to make a project app to download youtube videos on local or full guied for paging 3?
Thank you for this informative video
hi Phillip can you do the tutorial regarding login and sign up using jetpack compose and room database thank you very much, I really need this course
thanks man, using the Jetpack security library do have any tutorial around using it with Datastore
Is this using Groovy rather than Kotlin DSL? I'm having trouble following it. - Answer is yes by the way.
this using only Groovy (all old videos using Groovy) ,, Kotlin DSL is new 2023
@@OP-pv6un Ah I only really started Android in 2023 so didn't realize it was so new. Thanks.
Cool 😎
Thank you. I like this kind of movies.
Hey! I use Firebase Firestore to read The Base URL and API KEY's also how's that ? and with this approach I also change dynamic change things ??
very cool video
thank you BRO 👍👍👍
Hi Brother Philipp can you please create a guide video for becoming an Android Developer using Kotlin...
Specially for Students in College..
Like where to follow the materiel...
Please a New video on this topic will be lit 😊 Please...
Yaar you can start with Udacity courses. Trust me, they are free and top notch! I am speaking with experience because I asked the same question last year...
Hi Philip. We can use KMS to protect the Api Keys. Please make video on that.
If I put my API Key in my server, then my server also has a server token which validates requests from either app or hacker sites. But now the question is, the server token is still in my app !! Hackers can get it and use it to find the actual API key !!
be careful if you use multiple module structure. there is need to pay attention - which gradle to update
I Put everything together as you showed but as soon as i Push the minified APK on github IT revokes my github key, i build a Kind of App Store so i could easily Download newer Versions of my build Apps across my devices and IT pulles the Apps from github. Any Idea what i could Change so IT does Not revoke it? Do i need to make it Serverside?
Nice.. 👍 See if you can make video on hide api keys by using NDK CMake. Would be love to see it.. 😊
No can hide api key in client side as reverse engineers intercepts app traffic using proxy then then can find the api key from the request params
Its good to use API keys only on the server, but if someone is faking a client, then its possible to attack the server with replay attacks. So we need to secure also the communication with the server. And how can we tell the server that we are the original client? We still need an API key for our server?
If the server uses it, the client can't abuse it though but only via the API the server exposes. If the server has a rate limit for example the client can't do anything about it since they still don't know the key. And if the server is really strict with incoming params the client can't get more info than a normal logged in user for example
insightful
Helloooo! Little offtopic here. Could you suggest some good, comfy android developers / freelancers community in discord? I'm trying to go that route, but I tend to lose hope while being alone, you know? Thanks for your vids, btw! They're awesome!
Thanks bro, is very vedio.
DO NOTE
with smali editing, it is possible that someone could invoke Log.v on variables until an api key like value is reported
if function chaining is done, eg
FUNC(SECURE_GET());
then one could unchain this to see what SECURE_GET returns
great great great
if you could make a video about how to use Cmake to secure Api key
it will be good
Moral: We can only slow down the reverse engineering, Can't completely block third-party access to the API 🙂
i would rather put my api keys and keystore in my private app center account and access in my gradle file through build.gradle, in this it wont be exposed as plain text, whats ur say?
Will this approach stop Google Play team to give an error of "Leaked GCP API Keys"?
philip can you please make a video about paging 3 with rick and morty API and room caching
Hey Philipp, thanks for making this video, this might be helpful to secure API Keys to major extent. And Can you also help us secure different API Keys with same Key name for different builds?
Please make a video to secure api keys from NDK.
make jni folder and create file C to save the key and then use NDK to load the library, I think this is the best way.
Can still be found by reverse engineering
Decompiling APK won’t work with NDK but hacker can use deassembler and check .so files. NDK is still better than saving in build.gradle. It makes life of a hacker a little difficult
Do not put keys in plain string format in jni. Anyone can find .so file and extract that one.
is Same if you cerated in Build Type release ?? buildconfigfield
I like your videos. Can you create a video explaining how to prevent our app from rooted devices?
Prevent them being installed on rooted devices?? why would you want that??
Can You do a video on Securing webservices calls
How about to secure room DB and encryption the record inside the room
you said that i can get this key with other tools revers engineering?
what aabout an API_KEY
Hey guys, I have a doubt, If i put this apiKeys as local files how do you guys send them to github, or CD/CI softwares ?
You'll need to create the local.properties file with your API key using a script step before building the project
Please make one video for firebase rulse for specific app.
Hello, Thank for the information, I just want to ask you a question, Can we store api key using native code with C++ ?? is that a legal way to put api keys in code ?
it a is legal way, and I think it is more safe to store it there. But you should not store your API key in native code just like that. Make some magic function that builds your API key, so it is really hard to read the assembler code with some confused logic and get your API key
what about the team member checks the data of the API file using debug mode? whats the purpose of hiding from team members?
Hi @philip,
How about api key for Admob ads or fb ads?
Can I save it in EncryptedSharedPreferences? Or attackers can decrypt that?
How are you going to do that? You'll have a function call somewhere where you save the plain text api key in shared pref and therefore the key will be in memory once.
@@PhilippLackner oh right 😅
Downloading api key through firebase is meanless, as nothing prevents attackers from making app with the same package name and google-services and obtaining keys on launch.
I also used minSdk 21, but Android auto requires 23, so I bumped a little.
what if we want to share across other dev
Hi,
Can you create some videos about firebase function with firestore ?
Thank you
Did already
@@PhilippLackner Sorry i mean "cloud firestore function triggers".
Sir Your video Help me Alot in Andorid development Thanks Alot to keep it simple
Why are you still using Groovy gradle scripts, not Kotlin DSL? 😒
This is so good, thanks a lot, but I think this solution is not the best, the attacker can access the key if he have experience on attacking, I think I have something more secure I wanna share that in next comment, and if that is good or not please discuss me about that, thanks a lot, have a nice day.
why in my code Properties not resolved
Another solution is store api key inside an encrypted prepopulate local database
How do you want to pre-populate it? At some place in your code you'll have to do that and the API key will be the parameter for that function in clear text.
@@PhilippLackner prepopulate a Room database from a prepackaged database file that is located apk assets directory.
@@shmnysm7481 Then the key will be somewhere in your code to decrypt it. Again, you can make it harder of course, but if someone really wants it, they'll find it.
I am using NDK to secure my keys.
I need a little help from you sir
How can we get to communicate with each other.
I need a little help with something.
What if we make a cmake file and put api keys inside that ? Then use .gitignore.
how would you use a cmake file??
Gradle in not the secure way to put keys. Anyone can find BuildConfig file after reverse engineer and extract that one easily.
Congrats for not fully watching the video
Please make the sound a little louder.
What's the difference between the approach you showed in your dictionary app series and this one??
Please explain a bit.
Thank you! ❤️❤️❤️
I don't remember what I did there haha
@@PhilippLackner What you did is :
In app gradle
buildConfig("String", "API_KEY", API_KEY) instead of properties etc
Is this the same as new approach??
👌👍
not useful, anyone can crack the key and API hit during the call, with network trace.
Hey bro
There is no secure by this way :D
I think you never reverse app to get API key before :D
This way just hide the key from source code, but when you build to apk file...the key must be provide and compress inside apk file :D
Oh, another one who didn't watch the video
@@PhilippLackner Yes I did. You can easy to retrieve the API key by RE
🌹🤗
This may sound childish. But wont keeping our own safe word for the variable name "API_KEY" to something like "AWOOGA" make it difficult for them🤣
edit:
oh nvm. I just reached the end of video, and already realised the minifyenabled does the job
Just call it ENCRYPTED_API_KEY, they'll think they can't use it and won't even try🌝
@@PhilippLackner 🤣🤣🤣🤣
This one felt a bit like click bait 😅"How to hide and protect" - "you can't", but only said after half the video content