diff --git a/main/ui/src/main/java/org/cryptomator/ui/keyrecovery/WordEncoder.java b/main/ui/src/main/java/org/cryptomator/ui/keyrecovery/WordEncoder.java new file mode 100644 index 000000000..d5d3dc091 --- /dev/null +++ b/main/ui/src/main/java/org/cryptomator/ui/keyrecovery/WordEncoder.java @@ -0,0 +1,97 @@ +package org.cryptomator.ui.keyrecovery; + +import com.google.common.base.Preconditions; +import com.google.common.base.Splitter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +class WordEncoder { + + private static final int WORD_COUNT = 4096; + private static final char DELIMITER = ' '; + + private final List words; + private final Map indices; + + public WordEncoder() { + this("/i18n/4096words_en.txt"); + } + + public WordEncoder(String wordFile) { + try (InputStream in = getClass().getResourceAsStream(wordFile); // + Reader reader = new InputStreamReader(in, StandardCharsets.US_ASCII.newDecoder()); // + BufferedReader bufferedReader = new BufferedReader(reader)) { + this.words = bufferedReader.lines().limit(WORD_COUNT).collect(Collectors.toUnmodifiableList()); + } catch (IOException e) { + throw new IllegalArgumentException("Unreadable file: " + wordFile, e); + } + if (words.size() < WORD_COUNT) { + throw new IllegalArgumentException("Insufficient input file: " + wordFile); + } + this.indices = Map.ofEntries(IntStream.range(0, WORD_COUNT).mapToObj(i -> Map.entry(words.get(i), i)).toArray(Map.Entry[]::new)); + } + + /** + * Encodes the given input as a sequence of words. + * @param input A multiple of three bytes + * @return A String that can be {@link #decode(String) decoded} to the input again. + * @throws IllegalArgumentException If input is not a multiple of three bytes + */ + public String encodePadded(byte[] input) { + Preconditions.checkArgument(input.length % 3 == 0, "input needs to be padded to a multipe of three"); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < input.length; i+=3) { + byte b1 = input[i]; + byte b2 = input[i+1]; + byte b3 = input[i+2]; + int firstWordIndex = (0xFF0 & (b1 << 4)) + (0x00F & (b2 >> 4)); // 0xFFF000 + int secondWordIndex = (0xF00 & (b2 << 8)) + (0x0FF & b3); // 0x000FFF + assert firstWordIndex < WORD_COUNT; + assert secondWordIndex < WORD_COUNT; + sb.append(words.get(firstWordIndex)).append(DELIMITER); + sb.append(words.get(secondWordIndex)).append(DELIMITER); + } + if (sb.length() > 0) { + sb.setLength(sb.length() - 1); // remove last space + } + return sb.toString(); + } + + /** + * Decodes a String that has previously been {@link #encodePadded(byte[]) encoded} to a word sequence. + * @param encoded The word sequence + * @return Decoded bytes + * @throws IllegalArgumentException If the encoded string doesn't consist of a multiple of two words or one of the words is unknown to this encoder. + */ + public byte[] decode(String encoded) { + List splitted = Splitter.on(DELIMITER).omitEmptyStrings().splitToList(encoded); + Preconditions.checkArgument(splitted.size() % 2 == 0, "%s needs to be a multiple of two words", encoded); + byte[] result = new byte[splitted.size() / 2 * 3]; + for (int i = 0; i < splitted.size(); i+=2) { + String w1 = splitted.get(i); + String w2 = splitted.get(i+1); + int firstWordIndex = indices.getOrDefault(w1, -1); + int secondWordIndex = indices.getOrDefault(w2, -1); + Preconditions.checkArgument(firstWordIndex != -1, "%s not in dictionary", w1); + Preconditions.checkArgument(secondWordIndex != -1, "%s not in dictionary", w2); + byte b1 = (byte) (0xFF & (firstWordIndex >> 4)); + byte b2 = (byte) ((0xF0 & (firstWordIndex << 4)) + (0x0F & (secondWordIndex >> 8))); + byte b3 = (byte) (0xFF & secondWordIndex); + result[i/2*3] = b1; + result[i/2*3+1] = b2; + result[i/2*3+2] = b3; + } + return result; + } + + +} diff --git a/main/ui/src/main/resources/i18n/4096words_en.txt b/main/ui/src/main/resources/i18n/4096words_en.txt new file mode 100644 index 000000000..7e5945149 --- /dev/null +++ b/main/ui/src/main/resources/i18n/4096words_en.txt @@ -0,0 +1,4096 @@ +the +of +and +to +in +i +that +was +his +he +it +with +is +for +as +had +you +not +be +her +on +at +by +which +have +or +from +this +him +but +all +she +they +were +my +are +me +one +their +so +an +said +them +we +who +would +been +will +no +when +there +if +more +out +up +into +do +any +your +what +has +man +could +other +than +our +some +very +time +upon +about +may +its +only +now +like +little +then +can +should +made +did +us +such +a +great +before +must +two +these +see +know +over +much +down +after +first +Mr +good +men +own +never +most +old +shall +day +where +those +came +come +himself +way +work +life +without +go +make +well +through +being +long +say +might +how +am +too +even +def +again +many +back +here +think +every +people +went +same +last +thought +away +under +take +found +hand +eyes +still +place +while +just +also +young +yet +though +against +things +get +ever +give +god +years +off +face +nothing +right +once +another +left +part +saw +house +world +head +three +took +new +love +always +Mrs +put +night +each +king +between +tell +mind +heart +few +because +thing +whom +far +seemed +looked +called +whole +de +set +both +got +find +done +heard +look +name +days +told +let +lord +country +asked +going +seen +better +p +having +home +knew +side +something +moment +father +among +course +hands +woman +enough +words +mother +soon +full +end +gave +room +almost +small +thou +cannot +water +want +however +light +quite +brought +nor +word +whose +given +door +best +turned +taken +does +use +morning +myself +Gutenberg +felt +until +since +power +themselves +used +rather +began +present +voice +others +white +works +less +money +next +poor +death +stood +form +within +together +till +thy +large +matter +kind +often +certain +herself +year +friend +half +order +round +true +anything +keep +sent +wife +means +believe +passed +feet +near +public +state +son +hundred +children +thus +hope +alone +above +case +dear +thee +says +person +high +read +city +already +received +fact +gone +girl +known +hear +times +least +perhaps +sure +indeed +english +open +body +itself +along +land +return +leave +air +nature +answered +either +law +help +lay +point +child +letter +four +wish +fire +cried +2 +women +speak +number +therefore +hour +friends +held +free +war +during +several +business +whether +er +manner +second +reason +replied +united +call +general +why +behind +became +john +become +dead +earth +boy +lost +forth +thousand +looking +I'll +family +soul +feel +coming +England +spirit +question +care +truth +ground +really +rest +mean +different +making +possible +fell +towards +human +kept +short +town +following +need +cause +met +evening +returned +five +strong +able +french +live +lady +subject +sn +answer +sea +fear +understand +hard +terms +doubt +around +ask +arms +turn +sense +seems +black +bring +followed +beautiful +close +dark +hold +character +sort +sight +ten +show +party +fine +ye +ready +story +common +book +electronic +talk +account +mark +interest +written +can't +bed +necessary +age +else +force +idea +longer +art +spoke +across +brother +early +ought +sometimes +line +saying +table +appeared +river +continued +eye +ety +sun +information +later +everything +reached +suddenly +past +hours +strange +deep +change +miles +feeling +act +meet +paid +further +purpose +happy +added +seem +taking +blood +rose +south +beyond +cold +neither +forward +view +I've +position +sound +none +entered +clear +road +late +stand +suppose +la +daughter +real +nearly +mine +laws +knowledge +comes +toward +bad +cut +copy +husband +six +France +living +peace +didn't +low +north +remember +effect +natural +pretty +fall +fair +service +below +except +American +hair +London +laid +pass +led +copyright +doing +army +run +horse +future +opened +pleasure +history +west +pay +red +an' +4 +hath +note +although +wanted +gold +makes +desire +play +master +office +tried +front +big +Dr +lived +certainly +wind +receive +attention +government +unto +church +strength +length +company +placed +paper +letters +probably +glad +important +especially +greater +yourself +fellow +bear +opinion +window +ran +faith +ago +agreement +charge +beauty +lips +remained +arm +latter +duty +send +distance +silence +foot +wild +object +die +save +gentleman +trees +green +trouble +smile +books +wrong +various +sleep +persons +blockquote +happened +particular +drew +minutes +hardly +walked +chief +chance +according +beginning +action +deal +loved +visit +thinking +follow +standing +knows +try +presence +heavy +sweet +plain +donations +immediately +wrote +mouth +rich +thoughts +months +u +won't +afraid +Paris +single +joy +enemy +broken +unless +states +ship +condition +carry +exclaimed +including +filled +seeing +influence +write +boys +appear +outside +secret +parts +please +appearance +evil +march +george +whatever +slowly +tears +horses +places +caught +stay +instead +struck +blue +York +impossible +period +sister +battle +school +Mary +raised +occasion +married +man's +former +food +youth +learned +merely +reach +system +twenty +dinner +quiet +easily +moved +afterwards +giving +walk +stopped +laughed +language +expression +week +hall +danger +property +wonder +usual +figure +born +court +generally +grew +showed +getting +ancient +respect +third +worth +simple +tree +leaving +remain +society +fight +wall +result +heaven +William +started +command +tone +regard +expected +mere +month +beside +silent +perfect +experience +street +writing +goes +circumstances +entirely +fresh +duke +covered +bound +east +wood +stone +quickly +notice +bright +Christ +boat +noble +meant +somewhat +sudden +value +c. +direction +chair +due +support +tom +date +waiting +Christian +village +lives +reading +agree +lines +considered +field +observed +scarcely +wished +wait +greatest +permission +success +piece +British +ex +Charles +formed +speaking +trying +conversation +proper +hill +music +opportunity +that's +German +afternoon +cry +cost +allowed +girls +considerable +c +broke +honour +seven +private +sit +news +top +scene +discovered +marriage +step +garden +race +begin +per +individual +sitting +learn +political +difficult +bit +speech +Henry +lie +cast +eat +authority +etc. +floor +ill +ways +officers +offered +original +happiness +flowers +produced +summer +provide +study +religion +picture +walls +personal +America +watch +pleased +leaves +declared +hot +understood +effort +prepared +escape +attempt +supposed +killed +fast +author +Indian +brown +determined +pain +spring +takes +drawn +soldiers +houses +beneath +talking +turning +century +steps +intended +soft +straight +matters +likely +corner +trademark +justice +simply +produce +trust +appears +Rome +laugh +forget +Europe +passage +eight +closed +ourselves +gives +dress +passing +terrible +required +medium +efforts +sake +breath +wise +ladies +possession +pleasant +perfectly +o' +memory +usually +grave +fixed +modern +spot +troops +rise +break +fifty +island +meeting +camp +nation +existence +reply +I'd +copies +sky +touch +equal +fortune +v. +shore +domain +named +situation +looks +promise +orders +degree +middle +winter +plan +spent +allow +pale +conduct +running +religious +surprise +minute +roman +cases +shot +lead +move +names +stop +higher +et +father's +threw +worse +built +spoken +glass +board +vain +affairs +instance +safe +loss +doctor +offer +class +complete +access +lower +wouldn't +repeated +forms +darkness +military +warm +drink +passion +ones +physical +example +ears +questions +start +lying +smiled +keeping +spite +shown +directly +james +hart +serious +hat +dog +silver +sufficient +main +mentioned +servant +pride +crowd +train +wonderful +moral +instant +associated +path +greek +meaning +fit +ordered +lot +he's +proved +obliged +enter +rule +sword +attack +seat +game +health +paragraph +statement +social +refund +sorry +courage +members +grace +official +dream +worthy +rock +jack +provided +special +shook +request +mighty +glance +heads +movement +fee +share +expect +couldn't +dollars +spread +opposite +glory +twelve +space +engaged +peter +wine +ordinary +mountains +taste +iron +isn't +distribute +trade +consider +greatly +accepted +forced +advantage +ideas +decided +using +officer +rate +clothes +sign +feelings +native +promised +judge +difference +working +anxious +marry +captain +finished +extent +watched +curious +foreign +besides +method +excellent +confidence +marked +'em +jesus +exactly +importance +finally +bill +vast +prove +fancy +quick +yes +sought +prevent +neck +hearts +liberty +interesting +sides +legal +gentlemen +dry +serve +aside +pure +concerning +forgotten +lose +powers +possessed +thrown +evidence +distant +michael +progress +similar +narrow +altogether +building +page +particularly +knowing +weeks +settled +holding +mountain +search +sad +sin +lies +proud +pieces +clearly +price +ships +thirty +sick +honest +shut +talked +bank +fate +dropped +judgment +conditions +king's +accept +hills +removed +forest +measure +species +seek +highest +otherwise +stream +honor +carefully +obtained +ear +bread +bottom +additional +presented +aid +fingers +q +remembered +choose +agreed +animal +events +there's +fully +delight +rights +amount +obtain +tax +servants +sons +cross +shoulders +thick +points +stranger +woods +facts +dare +grow +creature +hung +rain +false +tall +gate +nations +created +refused +quietly +surface +freely +holy +streets +blow +july +regarded +fashion +report +coast +daily +file +shoulder +surprised +faces +succeeded +birds +distribution +royal +song +wealth +comfort +failed +freedom +peculiar +anyone +advance +gentle +surely +animals +waited +secure +desired +grass +touched +occupied +draw +stage +portion +expressed +opening +june +spirits +fish +tongue +capital +angry +growing +served +carriage +weather +breast +presently +snow +David +papers +necessity +practice +claim +hast +education +sharp +prince +permitted +group +enemies +robert +played +throughout +pity +expense +yours +million +add +pray +taught +explained +tired +leading +kill +shadow +companion +weight +mass +established +suffered +gray +brave +thin +satisfied +check +virtue +golden +numerous +frequently +famous +telling +powerful +alive +waters +national +weak +divine +material +principal +gathered +suggested +frank +valley +guess +finding +yellow +heat +remains +bent +seized +guard +equally +naturally +box +remarkable +gods +moon +slight +style +pointed +saved +windows +crossed +louis +pounds +ain't +evidently +principle +immediate +willing +consequence +richard +principles +characters +paul +season +remarked +science +tender +worked +grown +whispered +interested +quarter +midst +liked +advanced +apparently +bore +pwh +active +noticed +aware +thomas +uncle +list +dangerous +august +calm +genius +sacred +kingdom +entire +popular +unknown +nice +habit +spanish +familiar +reader +published +direct +handsome +you'll +joined +actually +kings +sd +posted +approach +Washington +hearing +needed +increased +walking +twice +throw +intellectual +appointed +wisdom +ceased +truly +numbers +demanded +priest +wounded +sorrow +drive +fault +listened +palace +affair +contact +distinguished +station +beat +distributed +e +listen +Italy +fool +becomes +watching +hurt +wants +express +occurred +favour +height +size +edge +subjects +task +follows +interests +nine +sympathy +burst +putting +dressed +lifted +hopes +suffer +noise +smiling +rode +tells +minds +farther +literature +vessel +affection +suffering +proceeded +flesh +advice +grand +carrying +legs +spain +post +collection +empty +rank +storm +god's +imagine +wore +duties +admitted +countries +pocket +arrival +imagination +driven +loud +sentence +lovely +extraordinary +November +December +happen +absence +breakfast +population +thank +rules +inhabitants +series +laughing +address +relief +bird +owner +impression +satisfaction +coat +prepare +relations +shape +birth +rapidly +smoke +January +mother+'s +machine +content +consideration +accompanied +regular +moving +stands +wholly +teeth +busy +treated +burning +shame +quality +bay +discover +inside +brain +soil +completely +message +ring +resolved +calling +phrase +acts +mention +square +pair +won +title +understanding +Sunday +fruit +mad +forces +included +tea +rocks +nearer +slaves +falling +absolutely +slow +bearing +mercy +larger +explain +contain +grief +soldier +wasn't +countenance +previous +explanation +welcome +proposed +prayer +stars +Germany +belief +informed +moments +poetry +constant +buy +final +faithful +ride +policy +supper +drawing +excitement +dying +demand +fighting +fields +drove +upper +sum +Philip +motion +assistance +forty +April +stones +Edward +fees +kindly +dignity +catch +October +seated +knees +amongst +current +sending +parties +objects +gained +bitter +possibly +slave +separate +loose +text +receiving +worst +sold +don +credit +chosen +hoped +printed +terror +features +fond +control +capable +fifteen +doesn't +firm +superior +cruel +spiritual +Harry +splendid +proof +pressed +sooner +join +process +crime +dust +instantly +lands +relation +doors +concerned +deeply +practical +colour +sing +destroy +anger +distributing +results +increase +reasons +nose +friendly +entrance +rooms +admit +supply +clean +useful +yesterday +delicate +fail +continue +remove +addressed +choice +huge +needs +wear +blind +unable +cover +double +victory +dozen +constantly +level +India +release +rough +ended +shows +fly +praise +devil +ahead +smith +connected +degrees +gain +addition +committed +chamber +notes +Italian +gradually +acquaintance +bought +souls +mission +sacrifice +cities +mistake +exercise +conscience +based +car +buried +theory +commanded +nobody +minister +closely +energy +dick +bare +fought +partly +mistress +hate +arose +playing +color +lake +safety +provisions +description +asleep +centre +faint +thinks +parents +escaped +careful +enjoy +drop +brilliant +brief +bringing +worship +goods +tale +skin +roof +grey +highly +crown +castle +excited +throne +stated +despair +ease +attached +total +kindness +mile +citizens +circle +dull +extreme +clouds +figures +intention +prison +term +assured +hidden +thoroughly +cup +member +civil +apply +labor +everywhere +intelligence +strike +fairly +comply +fellows +haven't +event +gently +connection +protection +conscious +edition +directed +pulled +flight +evident +surrounded +wishes +yards +voices +weary +couple +variety +whilst +volume +details +older +requirements +custom +apart +bow +awful +everybody +labour +asking +lover +showing +introduced +suit +becoming +composed +plans +rendered +pictures +lest +volunteers +singing +eager +precious +paused +require +meat +whenever +milk +dogs +successful +plants +vision +rare +granted +raise +Egypt +manners +cousin +you've +development +Arthur +obs +cool +trial +learning +approached +bridge +abroad +devoted +paying +literary +writer +fn +Israel +disappeared +interrupted +stock +readers +dreadful +female +protect +accustomed +Virginia +type +recognized +salt +destroyed +signs +innocent +temper +plenty +pope +avoid +hurried +represented +favor +mental +attitude +returning +admiration +brothers +anxiety +queen +teach +count +curiosity +solemn +causes +vessels +compelled +dance +hotel +wicked +fled +kissed +guns +fill +visible +younger +guide +earnest +actual +companions +prisoner +miserable +lad +harm +views +Irish +utterly +ends +shop +stairs +pardon +gay +beg +seldom +kinds +record +fat +sand +violent +branches +inquired +IV +September +worn +ireland +flat +departure +delivered +gift +ruin +skill +cattle +equipment +temple +calls +earlier +license +visited +en +consent +sufficiently +natives +wound +laughter +contained +perceived +scattered +whence +rushed +chiefly +bold +anywhere +witness +foolish +helped +kitchen +sell +anybody +self +extremely +treatment +throat +dreams +patient +speed +growth +quantity +Latin +immense +conclusion +computer +affected +severe +excuse +triumph +origin +Joseph +slept +eternal +thine +audience +pages +sounds +swift +limited +wings +stepped +services +library +remaining +containing +base +confusion +win +maid +charming +editions +attended +softly +reality +performed +glorious +likewise +site +sail +frightened +acquainted +unhappy +feared +article +prisoners +store +adopted +shalt +remark +cook +thousands +pause +inclined +convinced +band +valuable +hence +desert +effects +kiss +plant +ice +ball +stick +absolute +readily +behold +fierce +argument +observe +blessed +bosom +rage +striking +discovery +creatures +shouted +guilty +related +setting +forgot +punishment +gun +slightly +articles +police +mysterious +extended +confess +shade +murder +emotion +destruction +wondered +increasing +hide +expedition +horror +local +expenses +ignorant +doctrine +generous +range +host +wet +cloud +mystery +ed +waste +changes +possess +consciousness +February +trembling +disease +formerly +spend +production +source +mankind +universal +deck +sees +habits +estate +aunt +reign +humble +compliance +delay +shining +reported +hers +unfortunate +midnight +listening +flower +hero +accomplished +doth +classes +thanks +banks +philosophy +belong +finger +comfortable +market +cap +waves +woman's +glanced +troubled +difficulties +picked +european +purposes +somewhere +delighted +pushed +press +household +fleet +baby +region +lately +uttered +exact +image +ages +murmured +melancholy +suspicion +bowed +refuse +elizabeth +staff +liability +we'll +enjoyed +stretched +gaze +belonged +ashamed +reward +meal +blame +nodded +status +opinions +indicate +poem +savage +arise +voyage +misery +guests +painted +attend +afford +donate +job +proceed +loves +forehead +regret +plainly +risk +ad +lighted +angel +rapid +distinct +doubtless +properly +wit +fame +singular +error +utmost +methods +reputation +appeal +she's +w +strongly +Margaret +lack +breaking +dawn +violence +fatal +render +career +design +displayed +gets +commercial +forgive +lights +agreeable +suggestion +utter +sheep +resolution +spare +patience +domestic +concluded +'tis +farm +reference +chinese +exist +corn +approaching +alike +mounted +jane +issue +key +providing +majority +measures +towns +flame +Boston +dared +ignorance +reduced +occasionally +y +weakness +furnished +china +priests +flying +cloth +gazed +profit +fourth +bell +hitherto +benefit +movements +eagerly +acted +urged +ascii +disposed +electronically +atmosphere +chapter +begged +Helen +hole +invited +borne +departed +catholic +files +reasonable +sugar +replacement +sigh +humanity +thrust +frame +opposition +disk +haste +lonely +artist +knight +quarters +charm +substance +rolled +email +flung +celebrated +division +slavery +verse +decision +probable +painful +governor +forever +turns +branch +ocean +rear +leader +delightful +stared +boats +keen +disposition +senses +occasions +readable +beloved +inches +bones +enthusiasm +materials +luck +derived +managed +community +apparent +preserved +magnificent +hurry +scheme +oil +thence +reaching +dim +wretched +hanging +pipe +useless +nevertheless +print +smooth +solid +pursued +necessarily +build +attempted +centuries +eggs +equivalent +hastily +burned +you'd +recent +oh +travel +cries +noon +crying +generations +located +cabin +announcement +Britain +compared +handed +cease +smaller +circumstance +tent +frequent +alarm +nervous +beast +what's +aloud +independent +gates +distinction +essential +observation +stronger +recovered +belonging +loving +masters +writers +cf. +permanent +mortal +stern +gratitude +preserve +burden +aspect +millions +merry +knife +dread +clever +applicable +district +shadows +jim +silk +failure +links +cent +sentiment +amid +profits +agent +finds +Russia +bade +Russian +desperate +union +imagined +contempt +raising +lords +hell +separated +grant +seriously +tribes +hit +enormous +defective +conviction +secured +mixed +insisted +wooden +prefer +prayers +fever +selected +daughters +treat +warning +flew +speaks +developed +impulse +slipped +ours +Johnson +mistaken +damages +ambition +resumed +christmas +yield +ideal +schools +confirmed +descended +rush +falls +deny +calculated +correct +perform +hadn't +somehow +accordingly +stayed +acquired +counsel +distress +sins +notion +discussion +constitution +anne +hundreds +instrument +firmly +actions +steady +remarks +empire +elements +idle +pen +entering +online +africa +permit +th' +tide +vol +leaned +college +maintain +sovereign +tail +generation +crowded +fears +nights +limitation +tied +horrible +cat +displaying +port +male +experienced +opposed +treaty +contents +rested +mode +poured +les +occur +seeking +practically +abandoned +reports +eleven +sank +begins +founded +brings +trace +instinct +collected +Scotland +characteristic +chose +cheerful +tribe +costs +threatened +arrangement +western +sang +beings +sam +pressure +politics +sorts +shelter +rude +scientific +revealed +winds +riding +scenes +shake +industry +claims +pp. +merit +profession +lamp +interview +territory +sleeping +sex +coffee +devotion +thereof +creation +trail +Romans +supported +requires +fathers +prospect +obey +Alexander +shone +operation +northern +nurse +profound +hungry +Scott +sisters +assure +exceedingly +match +wrath +continually +rest. +gifts +folly +chain +uniform +debt +teaching +venture +execution +shoes +mood +crew +perceive +accounts +eating +multitude +declare +yard +o'er +astonishment +version +vague +odd +grateful +nearest +infinite +elsewhere +copying +apartment +activity +wives +parted +security +cared +sensible +owing +Martin +Saturday +cottage +Jews +leaning +capacity +joe +settle +referred +Francis +holder +involved +sunshine +Dutch +council +princes +ate +examination +steel +strangers +beheld +test +noted +slightest +widow +charity +realized +element +shed +errors +communication +reflection +attacked +organization +maintained +restored +folks +concealed +accordance +heavens +star +examined +deeds +wordforms +somebody +incident +oath +guest +bar +row +poverty +bottle +prevented +bless +stir +intense +completed +quarrel +touching +inner +available +fix +resistance +unusual +deed +derive +hollow +suspected +contains +sighed +province +deserted +establishment +vote +muttered +thither +oxford +cavalry +lofty +endure +succeed +leg +bid +alice +hated +civilization +u.s. +acting +landed +christians +passions +interior +scarce +lightly +disturbed +rev +supreme +hang +notwithstanding +shock +exception +offering +display +strain +drank +confined +o +exhausted +poets +sounded +aim +critical +jerusalem +directions +negro +fearful +standard +studied +bag +n +buildings +consequences +commenced +deeper +repeat +driving +beasts +track +rid +holds +residence +steadily +intimate +drinking +swear +treasure +fun +throwing +apt +enterprise +queer +seed +tower +runs +defend +favourite +desires +heavily +assembled +existed +depends +poems +hesitated +stuff +section +settlement +staring +sole +roads +plate +Mexico +overcome +pains +performing +dwell +grounds +taxes +marble +recently +tones +ability +awake +Walter +wave +shaking +folk +possibility +butter +fury +marched +Moses +writes +issued +sailed +instructions +hatred +pursuit +pull +furniture +additions +hid +rope +vi +adventure +royalty +vanished +arts +elder +signal +wanting +supplied +feast +safely +burn +describe +references +lesson +annual +card +passes +application +intelligent +county +beaten +presents +format +flow +sixty +scale +damage +marks +obtaining +moreover +commerce +startled +southern +consequently +outer +belongs +ben +wrought +average +naked +conducted +rivers +songs +obvious +foundation +concern +ceremony +magic +campaign +hunting +Carolina +liberal +whisper +largely +commonly +torn +exists +contributions +hunt +teacher +Christianity +lawyer +operations +detail +shortly +Caesar +wondering +leaders +blessing +princess +he'd +altar +tenderness +tiny +web +cardinal +sharply +regiment +chest +distinctly +purple +creating +gather +depth +indignation +performance +election +prosperity +gloomy +conception +clerk +decide +drunk +victim +reflected +pour +preceding +individuals +gazing +absurd +lift +gesture +armies +limbs +manage +brethren +Hugh +plays +hastened +dragged +motive +whatsoever +pointing +verses +pronounced +exchange +definite +emperor +tendency +remote +finish +flag +boots +enabled +administration +denied +churches +rarely +earnestly +considering +previously +ugly +bears +signed +genuine +harmless +mingled +obedience +walks +training +badly +feed +central +contrast +relieved +romance +Mississippi +structure +payment +pace +passages +succession +persuaded +sources +inquiry +inspired +angels +roll +wilt +inch +troubles +perfection +Lee +wherever +owe +handle +advantages +trip +shoot +fortunate +newspaper +employment +fitted +refuge +misfortune +providence +owns +cutting +beard +stirred +tear +Dan +resist +Bob +depths +maiden +determine +commission +merchant +whereas +crossing +independence +lively +breeze +provinces +Jean +virtues +conceived +relative +solitary +smell +wandering +thereby +eighteen +locked +provision +courts +eaten +historical +regarding +Florence +preferred +pick +ruined +wherein +vanity +condemned +deliver +unexpected +desk +gross +lane +happens +represent +Billy +root +Holland +mud +respectable +cleared +feels +fruits +testimony +Milton +existing +bride +rang +ranks +responsibility +beating +disappointed +suitable +depend +judges +giant +grasp +arrive +simplicity +autumn +absent +legally +veil +gloom +doubtful +suspect +weapons +limits +determination +feeble +prophet +Shak +gathering +basis +examine +corrupt +payments +returns +laying +prize +instances +Greeks +d +they're +theatre +purchase +comparison +composition +rival +someone +realize +defeat +demands +foe +shared +consists +studies +balance +intercourse +ID +forming +slender +coach +criminal +knocked +silly +humour +masses +indifferent +recall +occupation +discourse +keeps +regions +intervals +assist +novel +intellect +leads +hither +tales +sale +revenge +Lucy +yonder +resources +jealous +we're +wheel +invitation +narrative +risen +burnt +sentiments +inferior +amusement +Marie +flash +recognize +swiftly +portrait +create +summoned +suggest +induced +conflict +fed +curse +disappointment +helpless +preparing +construction +Lincoln +zeal +responsible +indicated +groups +positive +Germans +attracted +vengeance +fort +club +cure +stout +missed +gracious +include +flood +satisfy +agony +respects +ventured +implied +Maria +stupid +seas +Spaniards +grain +enjoyment +wearing +indifference +conceal +horizon +pleasures +therein +precisely +Canada +day's +assume +registered +estimate +steep +route +gardens +visitor +closer +harmony +non +thunder +wire +graceful +crept +Greece +childhood +knee +saddle +supplies +weeping +mostly +paragraphs +unconscious +mutual +scorn +grows +external +agents +software +institutions +losing +universe +clock +attempts +instruction +injury +roots +receipt +jumped +dearest +sore +earliest +finest +enable +discipline +motives +fastened +introduction +converted +wilderness +confused +fancied +offices +slip +revolution +wedding +girl's +farmer +silently +fires +wept +behalf +reckon +responded +uncertain +neglected +stroke +exquisite +engagement +dirty +rolling +platform +messenger +privilege +admirable +offers +mischief +physician +imposed +organized +covering +student +daring +cave +wars +convey +he'll +sincere +tradition +gravely +combined +gallant +sensation +travelling +charges +submit +tragedy +specific +commander +inn +stiff +accompany +score +virgin +farewell +paradise +villages +hunger +trembled +favorite +criticism +proprietary +customs +cotton +Ruth +hospital +restrictions +outward +impressed +blows +plains +flashed +rent +prey +owed +longing +musical +satisfactory +ridiculous +sheet +disgrace +colored +shouldn't +originally +Samuel +wages +papa +gas +inevitable +extensive +leisure +deadly +chin +claimed +glow +husband's +emotions +Adam +jealousy +leaf +publication +Englishman +Allah +Jones +hostile +wandered +railway +translation +procession +betrayed +pound +admired +elected +Pierre +sunk +ruins +eastern +roses +citizen +reminded +deceived +tables +beach +starting +funeral +arrested +flour +feature +correspondence +consisted +counted +reserve +proceedings +roar +romantic +twenty-five +hut +strangely +absorbed +propose +seats +bark +reception +pleasing +attained +wake +research +prayed +monarch +clothing +dollar +illness +calmly +obeyed +heartily +pressing +daylight +warriors +jest +abruptly +washed +comment +metal +preparations +nerves +solution +pretended +sixteen +assembly +tobacco +entity +dwelling +depart +swung +bitterly +alteration +colony +disclaimers +wing +peaceful +lion +opportunities +alarmed +furnish +resting +accused +culture +writings +dwelt +conquered +trick +trusted +column +financial +cunning +preparation +drama +joke +entertained +mist +hypertext +shell +medicine +proofread +nest +reverence +situated +yielded +conceive +appointment +lessons +fetch +tomb +candle +offence +coarse +heap +mixture +homes +model +men's +defect +destined +occasional +fourteen +hint +knights +solicit +dreamed +objection +craft +acid +namely +Asia +neglect +data +weapon +confessed +arrangements +repose +complying +copied +pink +user +heels +grandfather +other's +income +i.e. +regards +streams +vigorous +accepting +bishop +lightning +authors +flames +observations +compressed +sport +powder +beds +orange +painting +shout +Austria +bath +careless +chap +derivative +roused +primitive +doorway +climbed +volumes +vulgar +arguments +1st +sunset +convenient +mail +recalled +wrapped +abode +planted +paint +surrender +establish +mild +promptly +appearing +department +parish +Stephen +nay +lit +handkerchief +basket +easier +deserve +quit +assurance +mirror +plot +yer +upward +sadly +secretary +adding +modest +dish +cares +straw +net +advised +heavenly +largest +proceeding +impatient +wounds +warmth +certainty +restless +meantime +rays +salvation +lovers +experiment +shores +today +tremendous +afforded +moonlight +intend +California +cultivated +flushed +Shakespeare +newspapers +rocky +pious +wont +steam +improvement +garments +Ned +treasury +merchants +perpetual +trained +products +affectionate +dispute +visitors +poison +proposition +maybe +rifle +warned +parting +shield +erected +employ +prevailed +talent +rises +climate +chairs +searched +unlike +recover +mate +arrange +fortunes +puzzled +committee +aged +Ohio +ashes +ghost +b +promises +bushes +effective +distinguish +manifest +comparatively +esteem +blew +revelation +wash +recognition +confession +clay +nonsense +trunk +management +undoubtedly +dried +Dorothy +chiefs +coal +stolen +earthly +restore +indirectly +lasted +selfish +renewed +canoe +protest +vice +races +deemed +temporary +pile +Frederick +chapel +moderate +spell +Massachusetts +upright +quoted +area +bone +solitude +instruments +formal +students +greatness +struggling +Monday +reproach +altered +grim +leaped +Venice +federal +questioned +editor +desirable +acknowledge +motionless +remedy +bestowed +pursue +representative +pole +gladly +linen +vital +sink +pacific +hopeless +dangers +gratefully +president +travelled +ward +nephew +ms +cheer +bloody +siege +commands +justified +Atlantic +stomach +improved +admire +openly +sailors +abide +advancing +forests +records +Polly +recorded +modification +dramatic +statements +upstairs +varied +letting +Wilson +comrades +sets +descent +whither +envy +load +pretend +folded +brass +internal +furious +curtain +healthy +obscure +summit +alas +fifth +center +faced +cheap +saints +colonel +Egyptian +contest +owned +adventures +exclusion +seize +chances +springs +alter +landing +fence +leagues +glimpse +statue +contract +luxury +artillery +doubts +saving +fro +string +combination +awakened +faded +arrest +protected +temperature +strict +contented +professional +intent +brother's +injured +neighborhood +Andrew +abundance +smoking +yourselves +medical +garrison +likes +corps +heroic +inform +wife's +retained +agitation +nobles +prominent +institution +judged +embrace +wheels +closing +damaged +pack +affections +eldest +anguish +surrounding +obviously +strictly +capture +drops +inquire +ample +remainder +justly +recollection +deer +answers +bedroom +purely +bush +plunged +thyself +joint +refer +expecting +madam +railroad +spake +respecting +Jan +columns +weep +identify +discharge +bench +Ralph +heir +oak +rescue +limit +unpleasant +anxiously +innocence +awoke +expectation +incomplete +program +reserved +secretly +we've +invention +faults +disagreeable +piano +defeated +charms +purse +persuade +deprived +electric +endless +interval +chase +heroes +invisible +well-known +occupy +Jacob +gown +cruelty +lock +lowest +hesitation +withdrew +proposal +destiny +recognised +commons +foul +loaded +amidst +titles +ancestors +types +commanding +madness +happily +assigned +declined +temptation +lady's +subsequent +jewels +breathed +willingly +youthful +bells +spectacle +uneasy +shine +formidable +stately +machinery +fragments +rushing +attractive +product +economic +sickness +uses +dashed +engine +ashore +dates +theirs +adv +clasped +international +leather +spared +crushed +interfere +subtle +waved +slope +floating +worry +effected +passengers +violently +donation +steamer +witnesses +specified +learnt +stores +designed +guessed +roger +timber +talents +heed +Jackson +murdered +vivid +woe +calculate +killing +Laura +savages +wasted +trifle +funny +pockets +philosopher +insult +den +representation +incapable +eloquence +dine +temples +Ann +sensitive +robin +appetite +wishing +picturesque +Douglas +courtesy +flowing +remembrance +lawyers +sphere +murmur +elegant +honourable +stopping +guilt +welfare +avoided +fishing +perish +sober +steal +delicious +infant +lip +Norman +offended +dost +memories +wheat +Japanese +humor +exhibited +encounter +footsteps +marquis +smiles +amiable +twilight +arrows +consisting +park +retire +economy +sufferings +secrets +na +halted +govern +favourable +colors +translated +stretch +formation +immortal +gallery +parallel +lean +tempted +frontier +continent +knock +impatience +unity +dealing +prohibition diff --git a/main/ui/src/test/java/org/cryptomator/ui/keyrecovery/WordEncoderTest.java b/main/ui/src/test/java/org/cryptomator/ui/keyrecovery/WordEncoderTest.java new file mode 100644 index 000000000..784c638b6 --- /dev/null +++ b/main/ui/src/test/java/org/cryptomator/ui/keyrecovery/WordEncoderTest.java @@ -0,0 +1,42 @@ +package org.cryptomator.ui.keyrecovery; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Random; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class WordEncoderTest { + + private static final Random PRNG = new Random(42l); + private WordEncoder encoder; + + @BeforeAll + public void setup() { + encoder = new WordEncoder(); + } + + @DisplayName("decode(encode(input)) == input") + @ParameterizedTest(name = "test {index}") + @MethodSource("createRandomByteSequences") + void encodeAndDecode(byte[] input) { + String encoded = encoder.encodePadded(input); + byte[] decoded = encoder.decode(encoded); + Assertions.assertArrayEquals(input, decoded); + } + + static Stream createRandomByteSequences() { + return IntStream.range(0, 30).mapToObj(i -> { + byte[] randomBytes = new byte[i * 3]; + PRNG.nextBytes(randomBytes); + return randomBytes; + }); + } + +} \ No newline at end of file