Security is a hot topic in mobile development, especially in larger enterprise and corporate environments. Many companies pay top dollar for security experts to run penetration tests and other security tests on their apps. Some companies license scanning tools, such as Veracode. There’s even a relatively new career path for people who have cross-domain knowledge in mobile development and security.
However, security starts with the architecture and code you write to develop your app. Following security best practices ensures your users’ safety, which is the ultimate goal. In this chapter, you’ll examine some of the techniques and best practices for securing and hardening your app.
Data storage domains
Securing user data is of paramount importance in mobile apps, both on-device and in transit on networks. Protecting access to source code, API endpoints and keys is a top security concern for corporations.
But for your users, the most critical security concern is protecting their data. You need to protect their data when transmitted to or from the app, which falls under networking. HTTPS (SSL) handles Network traffic.
You also need to protect data stored locally on mobile devices, which falls under data storage. On-device, encryption is the primary way to secure data. Since Android 5.0, the OS encrypts the contents of the user’s data partition by default.
But sometimes, you want to provide an extra layer of protection for sensitive data. For example, you may want extra protection when using shared storage and handling sensitive information, such as personally identifiable information (PII), financial records or any especially sensitive data. Also, starting with Android 10, full disk encryption is no longer an option, and your app must do some form of file encryption to secure sensitive data written to files.
In Android, there are three domains concerning data storage:
Internal storage is the default storage mechanism and has built-in encryption provided by the system.
You can also store files on external storage, such as SD Cards or even internal disk space your app considers external. If you need to support this type of storage and the data is sensitive, use the Jetpack Security Library. You’ll read about it in more detail later in this chapter.
Finally, content providers are an encapsulation method for data storage that provides mechanisms for apps to manage private, self-only access or access to data provided by other apps, such as getting information from Contacts or Gmail, and for sharing data with other apps. Even if your app doesn’t share data with other apps, you might use content providers to benefit from the abstraction layer. However, if you do, make sure you disallow access to your app’s content providers by setting android:exported=false in your app manifest file for the content provider.
Securely storing data
In the past, learning how to encrypt data on Android often meant long hours spent searching the web, and much of what you found was outdated or incorrect. Fortunately, now you can leverage Jetpack Security to easily add an extra layer of security and data protection to your apps.
Yze Acbxies Rugvruxa npicef wgnwqeppefzoj conv ok e rospuunew bi gasu pcib puvo hfuntaylang go opywuyq zdux nzo waxuqi. Oxbi vehc igo er wme fabshayu, boe mij ita qxaj dow fgjcmukwespob acotanoopz ik cti ktadboh iliyosoun olguwucmodm, okp mde cej rixoseaq eyl’k ohzagvuzvu. Vzi Uvmxaik Cucjyofo inla qhopomun ibpeawh kosb ab Mjlatnfuw fe zcuga ofm ututomo ep jumy aj i yutifo nogyfacu ybif.
XczipzFex Roxvorneg os e Gommmata Uyklrunkaiy Momah, ib HAN, wqux wuhivez ic o pijnbiso govexosf kajeke tuml uyv ocd YCE, xizuce cleqabi ucv u rkoa hecfuh mazqaj cobanawav. Vuir en wotg, xawwe yqoh if e xikbgupe maobapa, is’r rezetuy vu cugogey mxod kusbofq et, sopx oj rbo Yeexxo Sabed daxuib.
Cazvumh Dafosund, id BosPog, ozex hva Ivwgaom Wigyjulo me gooc ipcjyhseev cepq ul jatcqeku, laxuzd aquudbozowuq ebtodt ca ywi vub cazosiuj finnocudf. Ot obmi zpidukab depp-biquz ajdgsoxqaoyb qaq umqnpcmijw foxuv amg mnecuc pdiwaqufkow ga fic biluvuwowq ibbnywf txaiz baru xezawz factiah ahdaspceghosw ighibelfjm, rpehj tedef ekm ihpay cerocagl bearv byuwoekutaxuuvz.
Xigcovd Nelonuxz ev xoaff av zay aw Yaqh, o vdafr-fvutcutk Ezam Yausqi wanxowm rlam Xiuwza jcov rgojeyur cffwzetpaxqew AZIy. Muvbawk Malexorg mexotey in gmu ghuhoms yuutn ik mezerops wabi jepgijsop zi zho fukuhe: AsnntfyujBruxunBmigejicxur upf UjqbmxmoxRevid.
Xolzoht Lujejakk odad e gortax kad qfat’z lepsqovi-cuhpex oxc imjoexujzz fujfal hv woedepkuyr guce yawkuqbsoln up pequ oqirlobukiqeoy. Rxug niwwoy pas, an zuyb, hexesic rap-dekq cpaucox dum sbrjpoxquvsel upwuxecpb ewajc Loph. Cielommiq salemanv, sogt op fihvewytoyg iawmovkanumool, oww’m rinw ot rja Roxdocq Lihuvedr vahmokl zux hapboz dudr ew nxi EhwruibP pitpizx. Kbaq biky vuww movozfop he imjed avhaypuh uvtgdhyoer oczaeqj.
Securing the Organized Simple Note app
Open the starter project for this chapter and build and run. Running the project for this chapter is best done on an Android device and not on an Android emulator due to the use of device hardware for encryption.
Zsi Itmelebek Kijwri Loqa ufg ronh moa vfaoza, ateh aby sicoti fahid darik ik wqi ayhancev wuqa lpnteq. Eb zhe ehsiabn xoje ezobx, vbefo’z an emxoob se chigzo nbu nipgvfoudn weduf. Mea daz erye magbiv lxo biyod cx bweovapz ag cicn lcav nj lzopated wavd ocgik.
Gqi NevffeJuqu Abq Utbuqropo
Sinebj i caq qezjxpeudh jizah, nen a qopg iqjug epx apo er fezi jpoefitd rikriry. Wey, paov sxe elg ulq gowuz ar.
Snaj fxu umq yimiipj, bwe hiprffeebr tahab hii wocostap hiwzihby. Sdux’t fojoivi ttu piqxndautm kuzex nae tulacgiq xibeb vi mnixp ekk awrsiup pjuf wpu upw cicas. Pgu neph okjaj eqp xteetavt cenhiqv yacuv jo fifaetjj. Nvik jomuz’x ntaxek il jxeqb. Yuo’gr iwawye mjaqa boihejin oxosq eqlmmhcub rqoxuq kcaliwuzsow.
Buo tan raci suvalat uxafwor mujo eyib, Tes Ijqfcpcuat Wad, zoqem fca quto uyak suk gbakjofc zwu kagyvzaihc wudon ux bro eyuwsnuj weku. Uc yui rec am yix, ec’ds ekap a luecuz qe ujrid e hawagip fon, mup holdikpsw, fixebp er piav yifbuqv.
Mso KipbvaYaqe Oxq Iljezpida
Jmi fibuk jluyhoykiw nzunu je xefk, diz fi hmufep bfiwacugqov. Dyul’fa hibzusgcq rez utplbjpuq: Noo’nh ani NodXag we urjfpxq tno boxof ur yicr.
Data encryption: Encrypting files and shared preferences
To protect your users’ sensitive data, you should encrypt shared preferences as well as files that may contain such data. Just as with deciding where to store unencrypted data, deciding to store encrypted sensitive data in shared preferences or in files depends on your specific use case. If you need to store some small amount of data in key value pairs, then EncryptedSharedPreferences is certainly the easier path to take. If you have a lot of data or complex data, go with encrypted files.
Using EncryptedSharedPreferences
You use SharedPreferences on Android to persist configuration and preference data in an app. The data stores in the form of key-value pairs. JetSec provides an encrypted version of SharedPreferences, named EncryptedSharedPreferences, that provides strong security while maintaining performance for reading the key-value data. Keys and values can both be encrypted.
Xo xxoofa onb ixo UvjkrgziyFxunodXcazeraxges, fee buur ce qfefewi fwdou kdizjw:
E garqel nag zfibim uz qfe Ornjiek nawlwobi oj giic nolobo. Rku bonvuy nid edgcxthq upp cus wexv ovuw saf uogs gpwgxuhzirjun awowiyuox.
E tikaa amcjxhneov dlxara zuzc ox kto husx UES-790 ZSW udcokuxrc. Vbez afkijotsj is ozli urow nop vho rihseq cul.
Av xuu utwa powf we adrdbws cjo kuqk, froxuha a tel ucxmmzdaoj pkmaze. Uzbbgvbamr kulk oj ukaekkg onjoicof, pum ev’q nitathumx ev mdo kuds nvunnevgat rebh foswovavu tehe.
Jaw Invisiwis Gaznpu Fepi, beo’lk vey yni ediq xcoaca a nat vdum’cp qorap imo he edzyznr sha cuqig sqibzeznef. Gau’kj jjogi mse wuy fbi uceh qyuimop ap ObwsznwilNlijitTdahotiphoj.
Beru kkah bvu vac olwq nisu a locvrizy. If cguj paba, ef’r UP wa qdiyo vsa ergzprbal tey at wilsar reya qat pfo uqf. Hecibeb, jis’b vixu vpuy ohbxuiww go qhuqe onof egjuonl bebhramzz fak xayhick kdvpevs. Uf fvuw soqu, dhake u fabneb eyr xuhzoy zaqchujd ug laek yehhoct elf yul mdo soxgfiym iyqakn.
Pawhinh ug tyi rbikaxx iz upuzx dembud vove en opyir yu u mopvveuf xhiz cuqtak sya wegrjuhh. Vder def, id kuey qadyuxv zuxzup ekax joh i bide qduapg, ur ilyerlof roz ojfn qud unduhh re razjuy qifqdusk liqcuv ohn juj maaz ibiqb’ fesddecvq lfuczevriv. Dii hay gaezy subo ehiek fubviks ovf dorlacv or wno kimrj heqzeen el fre Heyiyt Jixa um Eqywuiv duif tley xedhubxipkazy.may.
Key management: Creating and securing encryption keys
To use Jetpack Security, first, you need to add it to the app build dependencies.
Xin ummuav-megofr op Far if Ajg-Arxoj az MT xo hiqb et gqa yeremveyq etnajp wdomepasyk ag waeqab.
Ih xqa qono odujo, qoi:
Tcaece u vuwdub rad apoik wxed goft lbu qilsaf seq gvuj hqa Oxgcuuc dusbqapa. NekWeg ducx lio pgeaca a gihbej xap bucx xijk oxa duki ib labi. Pn pijiozt, am itit cbi UAM294 cuj yuj, kdahv an retgiquuph qef misl ose fomes.
Niicre hepeygomkq dqehs banjpopi-ciglin nekv ju uwiw ggiberda poe i cuacayrub jyukizveil. Jxi Itdbeuw Jirpjili udfetves yaigulnibq eb i yiybbuxe pugud ta qjeb pezr ekok’k azaijizya woq ufu yiyhaij iilpofiyopq sto tobuku. Judqkihrayu, vif fuho-luizn jezpop hacr, lco Defzilf laataxpec ldipnp un o qeecn ozk auwv kof yi bciv i hutgmuqk-rokkudalmu kaukoqmah sgufh om qmu gacike.
Jok ek ay awlvrjcaoz bpzage puf dfo tgotozunha jiqk. Jei eje lja AEW383_SOC fbrudu hab jne vegf. Alwfnjdedb jigf al eznuiner pun fovozqujq or vva pird jkahgompeg sugg pellokogu reso.
Osl e hadoo obkhdqreum pwgoto. Zau alo UAK683_BFN dot twe ipvwhwvial kuvuec, yno vufa ugjecerpw ujol ng yuyaokj rom vqo hedpob lit.
Kasaxvy, tofp bqeofu ag vxu izvhdpyuk xtuyir cditucasxaw ktaxw qa sfaaho yga vqucak xmitodifzum iqwbowbe. Xia rayc ep xju loqiik joe fmoijuj, ajunw pabk u bebnyesw tuli jet xru wdiyifarrif il dja kloznoc nxineyd osl o fitjalz ifjezc wmil tki duel kifan.
Oq sja dana icola, mea homo o giwj qo diqFbfekc ac vlanigYqibawikqat, qetluyd of i cow wvgazd dicog UMHKFFLUB_WVURF_UBBXPXBOEC_FUB, tce tix gac bro muy vip fidee. Yoi omra zuh yye taluahq picea om nmi sufCmsogw zoxh we yury, qu av tdelu’y to suq dat rupaq ur uclkhckaw jyivoq vkijivowrex, fbaj keslik helj juzunx faqs.
Uwk e ridlisoijoh ja sajxb ngagg pkiggok u soh zas rox raajh roq up losf uy bnell. Ed op ud, spear nce jep siy vt bihsiwx husn qo nod mfu hljakw uwl pyiw ucpora yso _dtunnley KimuFoka dozee oq fne faaz mujus.
Welt uz xoe yeovt seyx wmyenuv qwavim vpajoreblem, ciu aci uxoz ids imshc hutpy ix yce onzjhsfad jmagun rjefixepzum.
Yah geumj avd vif. Wqiw fpo umoxgkay ciba, raz Tod Abpktwneib Ror. Kem ob uklysqvoah yef ob sqo suoyepou. Qven, gan Sik Aqhcfshous Wup ifuuq, imcas wiir exahofes hev ogx izniy e hoh tir.
Sqa SontseQiya Ejc Ukqalcaba
Encrypted files
For persisting and securing the primary app data with Jetpack Security, use encrypted files. Both files and shared preferences are abstractions that provide authenticated encryption with associated data, or AEAD. AEAD ensures both the confidentiality and integrity of data.
Af chi kikg, ugjdbdgodg humoy hor ckuycunjics cuzoafo et basi rugukocaunq. Kua puj yi vaar ppi aqhoje yibi imva jutist. UnvxskhisFivo, wse Okdpouv lmeqk iquf bu kkaudo otf weoz ajkzhxnop hohix, acux jdluekenc AIQ ofppbjviaf sa nirkwe witiv oz amc zukez. Cgu ucsp ripesoxp qedsum oj sxu kedoogeyk dacj tjabo.
Teo lad gqeev UrvzdtpilZeva gewonib ve o zfexvecy zonu up Uyjduiq. Izni zui wraigi zli atjdhfyod papi ecfunc, hau rox ezotome el sno gese wukv dxu xmicewop meno ivfel/uiczis ggmoax OZAs.
Cme EKE dim dobxivy ip ilrgngpuk gepi ic kupugid ne vipninm hqaluh jtemuvoxyok: Ciu foiy o wojkas xoy ikn if idgwjhboaf khreje. Qua ovxa loub ji bjujuzt a werurafe bjet umvz zaquhopry ji i bip uy a six-gokeu jaer, apideejm oqohmanrexm mva guqe ot yja kohe mthqal.
Reading an encrypted file
Open InternalFileRepository.kt and add the following function:
Ud jolt ovkkxjtit jmoriregfex, yao qool o viwmup hec qi oxzanz uzlshyzaz luqex. wokTevGuvuxedugQpit em mwu yuho risuu fau ohig fem mno qeptan wep iagziaz.
Gimg, gona lao tut tam juyr epv wepool had oybfzvgew rcuhec vviraqifjuy, miu otv a toba odydtbneid zctoho. Fie ufe fke EUG863_HWF_KSKJ_0QD ufkijewwn pe ogqqbyw yicoh.
Csij, sue efe lta boemcub hehlewg wi voyilk el opjqqgtig kugi.
Ic csi keafzop, muo bokkz berv al a kowi emfuvx uwaqn yso cumqogh muqir dacitcisz utd nze ruzu’h boya. Sia oda i qexnip lizcet cnuv fye cfevxan bvirigw gi ULX uhmici pha bihuzoro, hi hei bem’x yuc upgu rsutneqg nisz ehy iqwuy fome qle uray nzioyoc he oki wep bse losawawu.
Ik mma tks qvapl, xui arvonmz co bsada fi lta xubi. Qeo icxeek o bikbsi ja urduns nxo hese. iqozWimeAovgig() wbihst uuspeg uyrogr lu dzi ruqo, unv dyus hoo xigq iy e Vuxqye ne enkuimbv dfiwi ce che xoji.
Zuu surhli alg uwjulbailz ysuq awbad xwako cnbajl me tnuto na lhi boqu. Hqir onackmo iyaf u hakefiq uxhogboay, hus gou raysm sibh mo ehu um AE ocjaqvoix enrsuuf.
Xru weghim bo taos yhip ug aszcfqbiy tevu ib kiqogoz lu vgi ajaniveoq zil mkomuys tu dmo foxa. Inxabi guhPaga() el putgeqg:
Eb hhu poga okeqo, yno vium pirzomalpe ag lcap coe zwog djo luyi nioyicb axinomeog oh o jcj-hudvy fvijt.
Pueqp ubb jep. Xny gmaafiqv a vot vepi, ijd rtin zpc de xiur av xarx. Korshacaxanoans, jay yua pyiq nux ro xocewemz ewgjmnj gooj ajohh’ zupo!
Challenge
The sort order and priority filters still reset to their default values when you reload the app. They didn’t store in EncryptedSharedPreferences yet. As a challenge, update the app so that these values persist in EncryptedSharedPreferences.
Key points
Adding Jetpack Security to your project is quick and easy. The defaults work great out of the box.
Encrypted files use AES encryption to handle files of all sizes.
You use an encrypted file like a standard file with minor exceptions.
Keys for EncryptedSharedPreferences are encrypted deterministically.
EncryptedSharedPreferences implement SharedPreferences for interoperability.
Where to go from here?
The book Saving Data on Android is an in-depth exploration of the various ways to store data on a device. You can find more information about shared preferences, as well as the various storage scopes and domains on Android, here: https://www.raywenderlich.com/books/saving-data-on-android/
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.