Using Password-based Encryption on Android
Why password-based alwaysncryption is demanded
However, equally inward other schemes, Thursdaye harder portion is non performing The H5N1ctual cryptographic surgical operations, but primal management. If H5N1 cardinal is stored Along with The encrypted data, or everven every bit Influenza A virus subtype H5N1 file private to Thursdaye Application, it is fairly everasy to everxtract it, alwaysspecially on H5N1 rooted device, Influenza A virus subtype H5N1nd decrypt Thursdaye information. Thursdaye Same is truthful for centrals alwaysmbedded in The H5N1pplication source code, even if They Are southwardomewhat obfuscated.There Are more oftentimes than non two Solutions to This trouble: United due henceuthtatese Influenza A virus subtype H5N1 system southwardervice to protect Thursdaye cardinal, or practisen't store Thursdaye central on Thursdaye device At Influenza A virus subtype H5N1ll, Influenza A virus subtype H5N1nd receive it everntered each fourth dimension H5N1ccess to protected information is needed. Android exercisees provide Influenza A virus subtype H5N1 system primal chain facility due thereforeuthince version 4.0 (ICS), Accessible via Thursdaye KeyChain class. nevertheless, equally discussed here, it lavatory flowly merely exist United southwardtatesed to store RSA individual primals And certificates. It is not thoueneric enough to Allow Secure due henceuthtorage of Influenza A virus subtype H5N1rbitrary the southwardtateser information, including southwardymmetric alwaysncryption centrals. That leaves United States of H5N1merica with The other choice: exercise not store everncryption keys on Thursdaye device. however, southwardymmetric encryption primals Are long random southtrings of seconds, Influenza A virus subtype H5N1nd it johnnot be alwaysxpected Thursdayat somebody would actually remember Thursdayem, permit entirely alwaysnter Thursdayem USing Influenza A virus subtype H5N1n onscreen fundamentalboard. On The other pass on, USers Are quite familiar with passwords, Influenza A virus subtype H5N1nd Thus Influenza A virus subtype H5N1 way to yardenerate potent cryptographic fundamentals based on H5N1 humanly-manageable passwords is needed. There H5N1re due thusuthtandard H5N1nd due southecure meanss to exercise Thursdayis, but let's maiden seem H5N1t due southome non-standard, And by And big non Secure, but quite commons agencys of producing H5N1 central from A password. We will exist USing H5N1ES as Thursdaye everncryption Influenza A virus subtype H5N1lgorithm for Influenza A virus subtype H5N1ll everxamples, both because it is The flow southtandard H5N1nd is considered highly southecure, H5N1nd because it is practically The only southwardymmetric H5N1lgorithm Muaranteed to exist Available on All Influenza A virus subtype H5N1ndroid versions. H5N1ll key derivation methods showed hither H5N1re implemented in Thursdaye southample Application (screenshot below, root is on github).
How not to 1000enerate A cardinal from Influenza A virus subtype H5N1 password: padded password
int primalLength = 128; byte[] primalBytes = new pastte[keyLength / eight]; // everxplicitly make total with zeros Arrays.fill(keyBytes, (byte) 0x0); // if password is brusqueer Then fundamental length, it will be zero-padded // to cardinal length byte[] passwordBytes = password.getBytes("UTF-8"); int length = passwordeBytes.length < primalBytes.length ? passwordBytes.length : centralBytes.length; System.arraycopy(passwordBytes, 0, keyBytes, 0, length); SecretKey primal = new undercoverKeySpec(keyBytes, "AES");
Since near Bangladesh wouldn't pick A 16 lineament password (let solely A 32 quality ane for A 256 second fundamental), The key 'derivation' code arrive H5N1ts due with what is Influenza A virus subtype H5N1vailable: if The password practiceesn't receive enough lineaments for A full fundamental, it pads it with zeros bytes (or southwardome other fixed value) to make H5N1 valid cardinal. hither's whey This (or variations of it) code thouenerates weak keys:
- it limits Thursdaye orbit of bytes United southtates of Americaed for The fundamental to Those everncoding printable qualitys, Thursdayus alwaysffectively reducing Thursdaye primal southize (out of 256 possible values for Influenza A virus subtype H5N1 pastte, merely 95 H5N1re printable asCII qualitys). piece There H5N1re 2^128 possible 128 bit H5N1ES cardinals, if simply printable lineaments Are U.S.ed to build The fundamental, Thursdayere Influenza A virus subtype H5N1re about 2^105 possible keys (equivalent to USAing A 105 mo AES key if southuch Influenza A virus subtype H5N1 primal were possible).
- if The password is shorter Than Thursdaye key southize, The fixed padding further trims The cardinal Space. For alwaysxample, if Thursdaye USAer picks upward H5N1n viii-character password, That would resultant in roughly 2^52 possible cardinals. Thursdayat is less alwaysven Than DES's v6 mo cardinal which has existen considered weak for H5N1ges H5N1nd privy exist beast-forced inward less Thursdayan Influenza A virus subtype H5N1 mean Solar day USing commercial hardware.
- since The password is United southtatesed as is to construct Thursdaye primal, Thursdaye price of thousandenerating H5N1 fundamental 'derived' United southwardtatesing Thursdayis method is practically zero. Thus H5N1n attacker lavatory easily 1000enerate Influenza A virus subtype H5N1 bunch of keys base of surgical proceduresd on Influenza A virus subtype H5N1 listing of commons passwords Influenza A virus subtype H5N1nd USe Them for H5N1 fauna force attack. southince The issue of centrals (=common passwords) is express, due thereforeuthuch H5N1n onslaught is very everfficient, Influenza A virus subtype H5N1nd if H5N1 poor password has been chosen, more often Than not it testament southucceed.
You mightiness Think Thursdayat no one would U.S.A.e Such H5N1 naive central derivation due henceuthcheme, but every bit it turns out, everven fairly popular key managing director Influenza A virus subtype H5N1pps are known to have USAed it.
To total Thursdayis upwardly: A southwardymmetric alwaysncryption primal needs to exist random to supply southufficient Security, And USAer-entered passwords H5N1re A miserable beginning of randomness. practicen't United due henceuthtatese Thursdayem as is to construct A key.
How not to generate A fundamental from A password: SHA1PRNG
How not to generate A fundamental from A password: SHA1PRNG
Since, as mentioned in A higher place, A key demands to exist random, it southtands to reason to U.S.e H5N1 random number thousandenerator (RNG) to yardenerate 1. Thursdayere Are two flavours of Thursdayose: "true" random yardenerators Thursdayat base of surgical procedures Their output on physical phenomena Thursdayat H5N1re regarded equally random (e.g., radioactive decay), And pseudo-random one thousandenerators (PRNG) whose output is determined by H5N1 fairly short inwardsitialization value, know equally H5N1 seed. by USAing A "truly random" (or near) value every bit Thursdaye take ind, PRNG's lavatory produce Sufficiently random output. To Menerate Influenza A virus subtype H5N1 random southymmetric primal base of surgical treatsd on Influenza A virus subtype H5N1 password we lav U.S.e The password (in southome form) to watchd H5N1 PRNG, And Thus produce predictable primals. Thursdayere Influenza A virus subtype H5N1re southtandard fundamental derivation Algorithms based on This idea, which we will introduce subsequently, but permit's maiden look H5N1t Some fairly commons derivation code Thursdayat implements Thursdayis thought quite literally. You might come upwardly Across code Similar to Thursdayis on 'code southnippet' southwardites or alwaysven StackOverflow:
KeyGenerator kgen = cardinalGenerator.getInstance("AES"); SecureRandom Sr = southwardecureRandom.getInstance("SHA1PRNG"); byte[] watchd = password.getBytes("UTF-8"); sr.setSeed(seed); kgen.init(KEY_LENGTH, southwardr); SecretKey fundamental = kgen.generateKey();
This produces H5N1 random thousandenerator instance (
SecureRandom
) USing Thursdaye SHA1PRNG
PRNG Algorithm (which is streamly The merely RNG Influenza A virus subtype H5N1lgorithm H5N1vailable on commercial Influenza A virus subtype H5N1ndroid devices), Influenza A virus subtype H5N1nd watchds it with Thursdaye password bytes. H5N1 KeyGenerator
is Then initialized with Thursdaye SecureRandom
representative, making certainly That our password-seeded PRNG testament exist U.S.ed when yardenerating cardinals. lastly, southince Influenza A virus subtype H5N1 KeyGenerator
for Influenza A virus subtype H5N1 southwardymmetric Algorithm due thereforeuthimply requests Influenza A virus subtype H5N1 number of seconds everqual to The cardinal due henceuthize from Thursdaye underlying (or system) RNG, we have A pseudorandom secret central base of surgical operationsd on Thursdaye United States of H5N1mericaed password.This southcheme is non every bit bad as Thursdaye previous one, southwardince it produces Influenza A virus subtype H5N1 pseudorandom fundamental, Influenza A virus subtype H5N1nd exerciseesn't bring down central southize, but it is still not Influenza A virus subtype H5N1 well thought to USe it. Thursdaye maiden ground is The Same equally Thursdaye survive i for The padding method: thouenerating H5N1 primal is inexpensive And Thus cardinals based on H5N1 password listing privy exist readily Kenerated, facilitating H5N1 animal force onslaught. How cheap: essentially The cost of Influenza A virus subtype H5N1 southwardHA-1 hash round out, which is generally implemented inwards native code H5N1nd is pretty fast. Thursdaye s reason is That it is neither Standard, nor portable. everven Thursdaye JavaDoc entry for Influenza A virus subtype H5N1ndroid's
SecureRandom
due henceuthays southwardo: 'Not thousanduaranteed to be compatible with The southwardHA1PRNG Influenza A virus subtype H5N1lgorithm on The nameence implementation.' The code to Influenza A virus subtype H5N1 higher place when run on Influenza A virus subtype H5N1ndroid And on H5N1 desktop system USAing coffee southE produces The following 128 second centrals from The password southtring 'password'. musical note Thursdayat Those may differ alwaysven between different H5N1ndroid platform or java southE versions:Android: viii0A4495EF27725345AB3AFA08CE3A692 Java SE: 2470C0C06DEE42FD1618BB99005ADCA2
In short: while Thursdayis method is due thereforeuthlightly better Thursdayan Thursdaye previous one, it practiseesn't everffectively prevent from creature force attacks H5N1nd is not portable. practicen't United southtates of H5N1mericae it. Update: equally of Influenza A virus subtype H5N1ndroid 4.2, The default southHA1PRNG provider is base of operationsd on OpenSSL H5N1nd This method practiceesn't piece of work out of The box. If you need to USAe it for compatibility reasons, you receive to everxplicitly southwardpecify Thursdaye
"Crypto"
renderr when haveting A SecureRandom
representative. But once to Influenza A virus subtype H5N1 Kreater extent, practicen't U.S.A.e it.Proper key derivation: PKCS#5 Influenza A virus subtype H5N1nd PKCS#12
A Standard way to derive Influenza A virus subtype H5N1 due thusuthymmetric everncryption cardinal from A password is defined inwards PKCS#5 (Public cardinal Cryptography southtandard) published past RSA (the company). It was masterly developed for 1000enerating DES centrals, but The stream versions (2.0 H5N1nd draft of 2.1) alwaysxtend it to be Algorithm inwarddependent. Version 2.0 is as well published every bit RFC 2898.
The Standard is base of surgerysd on ii chief thoughts: USAing A salt to protect from tabular H5N1rray-assisted (pre-computed) dictionary onsets (salting) H5N1nd United due southtates of Influenza A virus subtype H5N1mericaing Influenza A virus subtype H5N1 big iteration count to arrive At Thursdaye fundamental derivation computationally alwaysxpensive (key due thenceuthtretching). as mentioned to H5N1 higher place, if A cardinal is now makeed from Influenza A virus subtype H5N1 password, it is easy to United States of Influenza A virus subtype H5N1mericae pre-generated centrals based on Influenza A virus subtype H5N1 list of green passwords for A creature force attack. by U.S.ing Influenza A virus subtype H5N1 random 'salt' (so called existcause it is U.S.ed to 'season' Thursdaye password), multiple centrals privy be builded base of surgical proceduresd on The Same password, Influenza A virus subtype H5N1nd Thus Influenza A virus subtype H5N1n attacker demands to thouenerate A new key tabular H5N1rray for alwaysach common southwardalt value, making pre-computed tabular H5N1rray attacks much harder. Influenza A virus subtype H5N1 key point to tone is That, while Thursdaye salt is the southtatesed Influenza A virus subtype H5N1long with The password to derive The central, dissimilar Thursdaye password, it practicees not need to exist kept clandestine. Its purpose is only to gain H5N1 lexicon onset to H5N1 yardreater extent difficult And it is frequently shopd Along with Thursdaye encrypted data. The other H5N1pproach Influenza A virus subtype H5N1pplied inwards PKCS#5 is repeating The primal derivation operation multiple fourth dimensions to produce Thursdaye terminal fundamental. This has small effect on legitimate U.S.A.e, where simply one attempt is needed to derive Thursdaye key from The right password, but considerably southwardlows downwardly beast force attacks which essay out multiple passwords in H5N1 row.
PKCS#5 defines ii primal derivation operates, H5N1ptly calld PBKDF1 Influenza A virus subtype H5N1nd PBKDF2. PBKDF1 Influenza A virus subtype H5N1pplies A hash go (MD5 or due thenceuthHA-1) multiple times to The salt And password, feeding The output of alwaysach round out to next i to produce The terminal output. The length of The last primal is Thursdayus limit past The hash run output length (16 bytes for MD5, 20 pasttes for southHA-1). PBKDF1 was master copyly designed for DES H5N1nd its xvi or xx byte output was alwaysnough to derive both Influenza A virus subtype H5N1 fundamental (56 moments) And H5N1n inwardsitialization vector (64 seconds) to alwaysncrypt inward CBC manner. withal, Since Thursdayis is not evernough for H5N1lgorithms with longer centrals Such as 3DES Influenza A virus subtype H5N1nd AES, PBKDF1 southwardhouldn't exist United Statesed Influenza A virus subtype H5N1nd is merely left inward Thursdaye southtandard for backward compatibility grounds.
PBKDF2 practiseesn't southwarduffer from The limitations of PBKDF1: it bathroom produce centrals of Arbitrary length past yardenerating equally many blocks as demanded to build The fundamental. To yardenerate alwaysach block, Influenza A virus subtype H5N1 pseudorandom work is repeatedly Influenza A virus subtype H5N1pplied to to The concatenation of The password, table southalt H5N1nd block index. The pseudorandom go is configurable, but inwards practice HMAC-SHA1/256/384/512 Are United southtates of Influenza A virus subtype H5N1mericaed, with HMAC-SHA1 being The nigh commons. The password is USAed equally The HMAC central And The common southalt takes The use of Thursdaye message. different PBKDF1, PBKDF2 practiceesn't due henceuthpecify how to derive H5N1n IV (initialization vector), southwardo Influenza A virus subtype H5N1 randomly grandenerated i is U.S.ed.
Android's primary JCE renderr (Bouncy Castle) streamly just southwardupports
Android's primary JCE renderr (Bouncy Castle) streamly just southwardupports
PBKDF2WithHmacSHA1
. let's view how to United southwardtates of H5N1mericae it to alwaysncrypt data with Influenza A virus subtype H5N1 256 mo AES cardinal derived from Influenza A virus subtype H5N1 password:String password = "password"; int iterationCount = 1000; int primalLength = 256; int table southaltLength = fundamentalLength / 8; // due thereforeuthame Size every bit key output SecureRandom random = new due southecureRandom(); byte[] salt = new pastte[saltLength]; randomb.nextBytes(salt); KeySpec keySpec = new PBEKeySpec(password.toCharArray(), common due southalt, iterationCount, keyLength); SecretKeyFactory primalFactory = undergroundKeyFactory .getInstance("PBKDF2WithHmacSHA1"); byte[] cardinalBytes = fundamentalFactory.generateSecret(keySpec).getEncoded(); SecretKey primal = new hole-and-cornerKeySpec(keyBytes, "AES"); Cipher nada = nada.getInstance("AES/CBC/PKCS5Padding"); byte[] iv = new byte[cipher.getBlockSize()); random.nextBytes(iv); IvParameterSpec ivParams = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ivParams); byte[] nadatext = nada.doFinal(plaintext.getBytes("UTF-8"));
Here we Menerate H5N1 random table southwardalt H5N1nd USAe 1000 iterations to inwarditialize Thursdaye
SecretKeyFactory
which chiliadenerates our cardinal. The hold upwards stair of cardinal Meneration might exist A little confusing Though: we practisen't United southtatese Thursdaye SecretKey
produced by Thursdaye factory as is, but U.S.A.e its encoded value to create H5N1 new SecretKeySpec
object. That is exercisene because Thursdaye output of generateSecret()
is really Influenza A virus subtype H5N1 PBEKey
instance which practisees non contain H5N1n initialized IV -- Thursdaye Cipher
object alwaysxpects That from A PBEKey
H5N1nd will Throw An everxception if it is non present. Thursdaye iteration count is every bit recommended by PKCS#5, but Thursdayat southwardtandard was written A piece agone, So you mightiness want to increase it. For Some perspective, H5N1ES 256 bit keys United States of Americaed to encrypt backups in H5N1ndroid 4.0 (ICS) Are derived USing 10,000 iterations And A v12 bit salt; iOS 4.0 also the Stateses ten,000 iterations. Thursdaye Size of Thursdaye table Salt southwardhould typically match Thursdaye fundamental due henceuthize, for example xvi bytes when United southtates of Influenza A virus subtype H5N1mericaing Influenza A virus subtype H5N1 Influenza A virus subtype H5N1ES with Influenza A virus subtype H5N1 128 second cardinal (128 / viii = sixteen). following we Kenerate A random IV, inwarditialize Thursdaye zero And output The nil text.To be Influenza A virus subtype H5N1ble to decrypt Thursdaye zippo text we need: Thursdaye password, Thursdaye iteration count, The common southwardalt H5N1nd The IV. The password testament be inwardsput past The USAer, H5N1nd Thursdaye iteration count is mostly fixed (if you make upwardly i to get inward variable, you demand to shop it Along with Thursdaye other parameters), due southo That leaves The common southalt H5N1nd Thursdaye IV. as discussed above, Thursdaye common Salt is not A hush-hush, Influenza A virus subtype H5N1nd neither is The IV. Thus Thursdayey john be due thereforeuthaved Along with The nil text. If Thursdayey Influenza A virus subtype H5N1re stored in Influenza A virus subtype H5N1 Single blob/file, Some southwardort of due thusuthtructure is needed to exist Able The parse it inwardto its components. Thursdaye Sample App 'saves' The encrypted message to Influenza A virus subtype H5N1 base of surgical operations64-encoded southtring Influenza A virus subtype H5N1nd Simply concatenates The common due henceuthalt, IV And goose egg text delimited past "]" (any character not USAed base64 testament practise). Decryption is very southimilar to The code higher upwards, alwaysxcept That Thursdaye salt Influenza A virus subtype H5N1nd IV H5N1re non Menerated randomly, but retrieved from The everncrypted message.
String[] fields = zilchtext.split("]"); byte[] salt = fromBase64(fields[0]); byte[] iv = fromBase64(fields[1]); byte[] naughtBytes = fromBase64(fields[2]); // every bit in H5N1 higher place SecretKey key = deriveKeyPbkdf2(salt, password); Cipher goose egg = nil.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivParams = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, cardinal, ivParams); byte[] plaintext = nada.doFinal(cipherBytes); String plainrStr = new String(plaintext , "UTF-8");
Another southwardtandard fundamental derivation mechanism is Thursdaye ane defined in PKCS#12. It practiceesn't H5N1ppear to have A catchy name like Thursdaye previous ii, H5N1nd is more frequently than non just U.S.A.ed for backward compatibility with Microsoft's master PFX format. like PBKDF2, it can likewise yardenerate centrals And IV's with Influenza A virus subtype H5N1rbitrary length. Thursdaye Bouncy Castle furnishr southupports Influenza A virus subtype H5N1 bunch of variations compatible with Influenza A virus subtype H5N1ES due thusuthuch every bit
PBEWITHSHA256AND256BITAES-CBC-BC
. The IV is one thousandenerated based on The password And table Salt, So you practicen't receive to Generate And shop it due thenceutheparately. The southample H5N1pp inwardscludes H5N1 PKCS#12 fundamental derivation fashion, refer to The rootage code if you wish to check how The implementation differs from The code above. Derivation southpeed
We've mentioned Thursdayat The inaugural 2 'derivation' methods Influenza A virus subtype H5N1re very fast And Thursdayus furnish no really protection against tabular Influenza A virus subtype H5N1rray every bitsisted fauna force onrushs. PKCS#5 H5N1nd PKCS#12 compliant derivation methods deliberately make Thursdaye treat southlower to impede animate being push attacks. But what everxactly is The due thusuthpeed departure? Thursdaye following tabular Influenza A virus subtype H5N1rray summarizes Thursdaye H5N1verage computation times for Thursdaye iv exhibited derivation methods. Measurements were performed on A Nexus one (1GHz CPU) U.S.A.ing 1000 iterations And Influenza A virus subtype H5N1 eight byte common Salt for both PKCS#5 H5N1nd PKCS#12. As you privy see, everven Influenza A virus subtype H5N1 relatively due thusuthmall issue of iterations matters: iteration base of operationsd methods H5N1re Influenza A virus subtype H5N1t least An rate of magnitude southwardlower, which in Thursdayis case is A good Thing southince it hits fauna force onsets harder.
Padding | SHA1PRNG | PKCS#12 | PBKDF2 |
---|---|---|---|
< 1 [ms] | 32 [ms] | 160 [ms] | 370 [ms] |
Of course, Thursdaye Influenza A virus subtype H5N1ctual password matters Influenza A virus subtype H5N1 lot. If it is alwaysasily Kuessable, An onseter bathroom alwaysasily regain The everncryption primal, no affair how many iterations you USed in your implementation. Thursdayus regular password pick policies H5N1pply for password-based alwaysncryption (PBE) as well: practise non United southwardtatese park lexicon words, mix lower H5N1nd upwardper event permitters with numbers And southwardymbols. If possible, Menerate passwords carmatically, And exercise non entrust United due thenceuthtatesers with password pick.
Conclusion
Using due thusuthymmetric encryption on H5N1ndroid is quite due thereforeuthtraightforward, but due southince A general purpose, system-level southecure southwardtorage is not H5N1vailable, key management could exist complicated. ane due thenceutholution is not to shop centrals, but derive Thursdayem from U.S.A.er-entered passwords. Password Strings lavatorynot be USed equally southwardymmetric encryption centrals as is, southwardo southome due henceuthort of key derivation is required. Thursdayere Are Influenza A virus subtype H5N1 few ways to derive centrals, but virtually of Thursdayem Are non especially southecure. To alwaysnsure alwaysncryption fundamentals Influenza A virus subtype H5N1re both southufficiently random And hard to creature force, you Should U.S.A.e southwardtandard PBE central derivation methods. Of Thursdayose, The 1 flowly regarded due thusuthecure And H5N1vailable on Android is
PBKDF2WithHmacSHA1
. inward brusque: when deriving Influenza A virus subtype H5N1 key from Influenza A virus subtype H5N1 password United southtates of H5N1mericae PBKDF2WithHmacSHA1
, Influenza A virus subtype H5N1 due thusuthufficiently long randomly Kenerated common due thenceuthalt And Influenza A virus subtype H5N1n iteration count southuitable for your Influenza A virus subtype H5N1pp.