Vous êtes sur la page 1sur 17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

InternetEngineeringTaskForce(IETF)D.M'Raihi
RequestforComments:6238Verisign,Inc.
Category:InformationalS.Machani
ISSN:20701721DiversinetCorp.
M.Pei
Symantec
J.Rydell
Portwise,Inc.
May2011
TOTP:TimeBasedOneTimePasswordAlgorithm
Abstract
ThisdocumentdescribesanextensionoftheOneTimePassword(OTP)
algorithm,namelytheHMACbasedOneTimePassword(HOTP)algorithm,
asdefinedinRFC4226,tosupportthetimebasedmovingfactor.The
HOTPalgorithmspecifiesaneventbasedOTPalgorithm,wherethe
movingfactorisaneventcounter.Thepresentworkbasesthemoving
factoronatimevalue.AtimebasedvariantoftheOTPalgorithm
providesshortlivedOTPvalues,whicharedesirableforenhanced
security.
Theproposedalgorithmcanbeusedacrossawiderangeofnetwork
applications,fromremoteVirtualPrivateNetwork(VPN)accessand
WiFinetworklogontotransactionorientedWebapplications.The
authorsbelievethatacommonandsharedalgorithmwillfacilitate
adoptionoftwofactorauthenticationontheInternetbyenabling
interoperabilityacrosscommercialandopensourceimplementations.
StatusofThisMemo
ThisdocumentisnotanInternetStandardsTrackspecification;itis
publishedforinformationalpurposes.
ThisdocumentisaproductoftheInternetEngineeringTaskForce
(IETF).ItrepresentstheconsensusoftheIETFcommunity.Ithas
receivedpublicreviewandhasbeenapprovedforpublicationbythe
InternetEngineeringSteeringGroup(IESG).Notalldocuments
approvedbytheIESGareacandidateforanylevelofInternet
Standard;seeSection2ofRFC5741.
Informationaboutthecurrentstatusofthisdocument,anyerrata,
andhowtoprovidefeedbackonitmaybeobtainedat
http://www.rfceditor.org/info/rfc6238.

M'Raihi,etal.Informational[Page1]
https://tools.ietf.org/html/rfc6238

1/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
CopyrightNotice
Copyright(c)2011IETFTrustandthepersonsidentifiedasthe
documentauthors.Allrightsreserved.
ThisdocumentissubjecttoBCP78andtheIETFTrust'sLegal
ProvisionsRelatingtoIETFDocuments
(http://trustee.ietf.org/licenseinfo)ineffectonthedateof
publicationofthisdocument.Pleasereviewthesedocuments
carefully,astheydescribeyourrightsandrestrictionswithrespect
tothisdocument.CodeComponentsextractedfromthisdocumentmust
includeSimplifiedBSDLicensetextasdescribedinSection4.eof
theTrustLegalProvisionsandareprovidedwithoutwarrantyas
describedintheSimplifiedBSDLicense.
TableofContents
1.Introduction....................................................2
1.1.Scope......................................................2
1.2.Background.................................................3
2.NotationandTerminology........................................3
3.AlgorithmRequirements..........................................3
4.TOTPAlgorithm..................................................4
4.1.Notations..................................................4
4.2.Description................................................4
5.SecurityConsiderations.........................................5
5.1.General....................................................5
5.2.ValidationandTimeStepSize..............................6
6.Resynchronization...............................................7
7.Acknowledgements................................................7
8.References......................................................8
8.1.NormativeReferences.......................................8
8.2.InformativeReferences.....................................8
AppendixA.TOTPAlgorithm:ReferenceImplementation...............9
AppendixB.TestVectors..........................................14
1.Introduction
1.1.Scope
ThisdocumentdescribesanextensionoftheOneTimePassword(OTP)
algorithm,namelytheHMACbasedOneTimePassword(HOTP)algorithm,
asdefinedin[RFC4226],tosupportthetimebasedmovingfactor.

M'Raihi,etal.Informational[Page2]
https://tools.ietf.org/html/rfc6238

2/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
1.2.Background
Asdefinedin[RFC4226],theHOTPalgorithmisbasedonthe
HMACSHA1algorithm(asspecifiedin[RFC2104])andappliedtoan
increasingcountervaluerepresentingthemessageintheHMAC
computation.
Basically,theoutputoftheHMACSHA1calculationistruncatedto
obtainuserfriendlyvalues:
HOTP(K,C)=Truncate(HMACSHA1(K,C))
whereTruncaterepresentsthefunctionthatcanconvertanHMACSHA1
valueintoanHOTPvalue.KandCrepresentthesharedsecretand
countervalue;see[RFC4226]fordetaileddefinitions.
TOTPisthetimebasedvariantofthisalgorithm,whereavalueT,
derivedfromatimereferenceandatimestep,replacesthecounterC
intheHOTPcomputation.
TOTPimplementationsMAYuseHMACSHA256orHMACSHA512functions,
basedonSHA256orSHA512[SHA2]hashfunctions,insteadofthe
HMACSHA1functionthathasbeenspecifiedfortheHOTPcomputation
in[RFC4226].
2.NotationandTerminology
Thekeywords"MUST","MUSTNOT","REQUIRED","SHALL","SHALLNOT",
"SHOULD","SHOULDNOT","RECOMMENDED","MAY",and"OPTIONAL"inthis
documentaretobeinterpretedasdescribedin[RFC2119].
3.AlgorithmRequirements
Thissectionsummarizestherequirementstakenintoaccountfor
designingtheTOTPalgorithm.
R1:Theprover(e.g.,token,softtoken)andverifier(authentication
orvalidationserver)MUSTknoworbeabletoderivethecurrent
Unixtime(i.e.,thenumberofsecondselapsedsincemidnightUTC
ofJanuary1,1970)forOTPgeneration.See[UT]foramore
detaileddefinitionofthecommonlyknown"Unixtime".The
precisionofthetimeusedbytheproveraffectshowoftenthe
clocksynchronizationshouldbedone;seeSection6.
R2:TheproverandverifierMUSTeithersharethesamesecretorthe
knowledgeofasecrettransformationtogenerateasharedsecret.
R3:ThealgorithmMUSTuseHOTP[RFC4226]asakeybuildingblock.

M'Raihi,etal.Informational[Page3]
https://tools.ietf.org/html/rfc6238

3/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
R4:TheproverandverifierMUSTusethesametimestepvalueX.
R5:ThereMUSTbeauniquesecret(key)foreachprover.
R6:ThekeysSHOULDberandomlygeneratedorderivedusingkey
derivationalgorithms.
R7:ThekeysMAYbestoredinatamperresistantdeviceandSHOULDbe
protectedagainstunauthorizedaccessandusage.
4.TOTPAlgorithm
ThisvariantoftheHOTPalgorithmspecifiesthecalculationofa
onetimepasswordvalue,basedonarepresentationofthecounteras
atimefactor.
4.1.Notations
oXrepresentsthetimestepinseconds(defaultvalueX=
30seconds)andisasystemparameter.
oT0istheUnixtimetostartcountingtimesteps(defaultvalueis
0,i.e.,theUnixepoch)andisalsoasystemparameter.
4.2.Description
Basically,wedefineTOTPasTOTP=HOTP(K,T),whereTisaninteger
andrepresentsthenumberoftimestepsbetweentheinitialcounter
timeT0andthecurrentUnixtime.
Morespecifically,T=(CurrentUnixtimeT0)/X,wherethe
defaultfloorfunctionisusedinthecomputation.
Forexample,withT0=0andTimeStepX=30,T=1ifthecurrent
Unixtimeis59seconds,andT=2ifthecurrentUnixtimeis
60seconds.
TheimplementationofthisalgorithmMUSTsupportatimevalueT
largerthana32bitintegerwhenitisbeyondtheyear2038.The
valueofthesystemparametersXandT0arepreestablishedduring
theprovisioningprocessandcommunicatedbetweenaproverand
verifieraspartoftheprovisioningstep.Theprovisioningflowis
outofscopeofthisdocument;referto[RFC6030]forsuch
provisioningcontainerspecifications.

M'Raihi,etal.Informational[Page4]
https://tools.ietf.org/html/rfc6238

4/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
5.SecurityConsiderations
5.1.General
Thesecurityandstrengthofthisalgorithmdependontheproperties
oftheunderlyingbuildingblockHOTP,whichisaconstructionbased
onHMAC[RFC2104]usingSHA1asthehashfunction.
Theconclusionofthesecurityanalysisdetailedin[RFC4226]is
that,forallpracticalpurposes,theoutputsofthedynamic
truncationondistinctinputsareuniformlyandindependently
distributedstrings.
Theanalysisdemonstratesthatthebestpossibleattackagainstthe
HOTPfunctionisthebruteforceattack.
Asindicatedinthealgorithmrequirementsection,keysSHOULDbe
chosenatrandomorusingacryptographicallystrongpseudorandom
generatorproperlyseededwitharandomvalue.
KeysSHOULDbeofthelengthoftheHMACoutputtofacilitate
interoperability.
WeRECOMMENDfollowingtherecommendationsin[RFC4086]forall
pseudorandomandrandomnumbergenerations.Thepseudorandomnumbers
usedforgeneratingthekeysSHOULDsuccessfullypasstherandomness
testspecifiedin[CN],orasimilarwellrecognizedtest.
AllthecommunicationsSHOULDtakeplaceoverasecurechannel,e.g.,
SecureSocketLayer/TransportLayerSecurity(SSL/TLS)[RFC5246]or
IPsecconnections[RFC4301].
WealsoRECOMMENDstoringthekeyssecurelyinthevalidationsystem,
and,morespecifically,encryptingthemusingtamperresistant
hardwareencryptionandexposingthemonlywhenrequired:for
example,thekeyisdecryptedwhenneededtoverifyanOTPvalue,and
reencryptedimmediatelytolimitexposureintheRAMtoashort
periodoftime.
ThekeystoreMUSTbeinasecurearea,toavoid,asmuchas
possible,directattackonthevalidationsystemandsecrets
database.Particularly,accesstothekeymaterialshouldbelimited
toprogramsandprocessesrequiredbythevalidationsystemonly.

M'Raihi,etal.Informational[Page5]
https://tools.ietf.org/html/rfc6238

5/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
5.2.ValidationandTimeStepSize
AnOTPgeneratedwithinthesametimestepwillbethesame.Whenan
OTPisreceivedatavalidationsystem,itdoesn'tknowaclient's
exacttimestampwhenanOTPwasgenerated.Thevalidationsystemmay
typicallyusethetimestampwhenanOTPisreceivedforOTP
comparison.Duetonetworklatency,thegap(asmeasuredbyT,that
is,thenumberoftimestepssinceT0)betweenthetimethattheOTP
wasgeneratedandthetimethattheOTParrivesatthereceiving
systemmaybelarge.Thereceivingtimeatthevalidationsystemand
theactualOTPgenerationmaynotfallwithinthesametimestep
windowthatproducedthesameOTP.WhenanOTPisgeneratedatthe
endofatimestepwindow,thereceivingtimemostlikelyfallsinto
thenexttimestepwindow.AvalidationsystemSHOULDtypicallyset
apolicyforanacceptableOTPtransmissiondelaywindowfor
validation.ThevalidationsystemshouldcompareOTPsnotonlywith
thereceivingtimestampbutalsothepasttimestampsthatarewithin
thetransmissiondelay.Alargeracceptabledelaywindowwould
exposealargerwindowforattacks.WeRECOMMENDthatatmostone
timestepisallowedasthenetworkdelay.
Thetimestepsizehasanimpactonbothsecurityandusability.A
largertimestepsizemeansalargervaliditywindowforanOTPtobe
acceptedbyavalidationsystem.Thereareimplicationsforusinga
largertimestepsize,asfollows:
First,alargertimestepsizeexposesalargerwindowtoattack.
WhenanOTPisgeneratedandexposedtoathirdpartybeforeitis
consumed,thethirdpartycanconsumetheOTPwithinthetimestep
window.
WeRECOMMENDadefaulttimestepsizeof30seconds.Thisdefault
valueof30secondsisselectedasabalancebetweensecurityand
usability.
Second,thenextdifferentOTPmustbegeneratedinthenexttime
stepwindow.Ausermustwaituntiltheclockmovestothenext
timestepwindowfromthelastsubmission.Thewaitingtimemaynot
beexactlythelengthofthetimestep,dependingonwhenthelast
OTPwasgenerated.Forexample,ifthelastOTPwasgeneratedatthe
halfwaypointinatimestepwindow,thewaitingtimeforthenext
OTPishalfthelengthofthetimestep.Ingeneral,alargertime
stepwindowmeansalongerwaitingtimeforausertogetthenext
validOTPafterthelastsuccessfulOTPvalidation.Atoolarge
window(forexample,10minutes)mostprobablywon'tbesuitablefor
typicalInternetloginusecases;ausermaynotbeabletogetthe
nextOTPwithin10minutesandthereforewillhavetorelogintothe
samesitein10minutes.

M'Raihi,etal.Informational[Page6]
https://tools.ietf.org/html/rfc6238

6/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
NotethataprovermaysendthesameOTPinsideagiventimestep
windowmultipletimestoaverifier.TheverifierMUSTNOTaccept
thesecondattemptoftheOTPafterthesuccessfulvalidationhas
beenissuedforthefirstOTP,whichensuresonetimeonlyuseofan
OTP.
6.Resynchronization
Becauseofpossibleclockdriftsbetweenaclientandavalidation
server,weRECOMMENDthatthevalidatorbesetwithaspecificlimit
tothenumberoftimestepsaprovercanbe"outofsynch"before
beingrejected.
Thislimitcanbesetbothforwardandbackwardfromthecalculated
timesteponreceiptoftheOTPvalue.Ifthetimestepis
30secondsasrecommended,andthevalidatorissettoonlyaccept
twotimestepsbackward,thenthemaximumelapsedtimedriftwouldbe
around89seconds,i.e.,29secondsinthecalculatedtimestepand
60secondsfortwobackwardtimesteps.
Thiswouldmeanthevalidatorcouldperformavalidationagainstthe
currenttimeandthentwofurthervalidationsforeachbackwardstep
(foratotalof3validations).Uponsuccessfulvalidation,the
validationservercanrecordthedetectedclockdriftforthetoken
intermsofthenumberoftimesteps.WhenanewOTPisreceived
afterthisstep,thevalidatorcanvalidatetheOTPwiththecurrent
timestampadjustedwiththerecordednumberoftimestepclockdrifts
forthetoken.
Also,itisimportanttonotethatthelongeraproverhasnotsent
anOTPtoavalidationsystem,thelonger(potentially)the
accumulatedclockdriftbetweentheproverandtheverifier.Insuch
cases,theautomaticresynchronizationdescribedabovemaynotwork
ifthedriftexceedstheallowedthreshold.Additional
authenticationmeasuresshouldbeusedtosafelyauthenticatethe
proverandexplicitlyresynchronizetheclockdriftbetweenthe
proverandthevalidator.
7.Acknowledgements
Theauthorsofthisdocumentwouldliketothankthefollowingpeople
fortheircontributionsandsupporttomakethisabetter
specification:HannesTschofenig,JonathanTuliani,DavidDix,
SiddharthBajaj,StuVeath,ShuhChang,OanhHoang,JohnHuang,and
SiddharthaMohapatra.

M'Raihi,etal.Informational[Page7]
https://tools.ietf.org/html/rfc6238

7/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
8.References
8.1.NormativeReferences
[RFC2104]Krawczyk,H.,Bellare,M.,andR.Canetti,"HMAC:Keyed
HashingforMessageAuthentication",RFC2104,
February1997.
[RFC2119]Bradner,S.,"KeywordsforuseinRFCstoIndicate
RequirementLevels",BCP14,RFC2119,March1997.
[RFC4086]Eastlake3rd,D.,Schiller,J.,andS.Crocker,
"RandomnessRecommendationsforSecurity",BCP106,
RFC4086,June2005.
[RFC4226]M'Raihi,D.,Bellare,M.,Hoornaert,F.,Naccache,D.,and
O.Ranen,"HOTP:AnHMACBasedOneTimePassword
Algorithm",RFC4226,December2005.
[SHA2]NIST,"FIPSPUB1803:SecureHashStandard(SHS)",
October2008,<http://csrc.nist.gov/publications/fips/
fips1803/fips1803_final.pdf>.
8.2.InformativeReferences
[CN]Coron,J.andD.Naccache,"AnAccurateEvaluationof
Maurer'sUniversalTest",LNCS1556,February1999,
<http://www.gemplus.com/smart/rd/publications/pdf/
CN99maur.pdf>.
[RFC4301]Kent,S.andK.Seo,"SecurityArchitectureforthe
InternetProtocol",RFC4301,December2005.
[RFC5246]Dierks,T.andE.Rescorla,"TheTransportLayerSecurity
(TLS)ProtocolVersion1.2",RFC5246,August2008.
[RFC6030]Hoyer,P.,Pei,M.,andS.Machani,"PortableSymmetric
KeyContainer(PSKC)",RFC6030,October2010.
[UT]Wikipedia,"Unixtime",February2011,
<http://en.wikipedia.org/wiki/Unix_time>.

M'Raihi,etal.Informational[Page8]
https://tools.ietf.org/html/rfc6238

8/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
AppendixA.TOTPAlgorithm:ReferenceImplementation
<CODEBEGINS>
/**
Copyright(c)2011IETFTrustandthepersonsidentifiedas
authorsofthecode.Allrightsreserved.
Redistributionanduseinsourceandbinaryforms,withorwithout
modification,ispermittedpursuantto,andsubjecttothelicense
termscontainedin,theSimplifiedBSDLicensesetforthinSection
4.coftheIETFTrust'sLegalProvisionsRelatingtoIETFDocuments
(http://trustee.ietf.org/licenseinfo).
*/
importjava.lang.reflect.UndeclaredThrowableException;
importjava.security.GeneralSecurityException;
importjava.text.DateFormat;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjavax.crypto.Mac;
importjavax.crypto.spec.SecretKeySpec;
importjava.math.BigInteger;
importjava.util.TimeZone;
/**
*ThisisanexampleimplementationoftheOATH
*TOTPalgorithm.
*Visitwww.openauthentication.orgformoreinformation.
*
*@authorJohanRydell,PortWise,Inc.
*/
publicclassTOTP{
privateTOTP(){}
/**
*ThismethodusestheJCEtoprovidethecryptoalgorithm.
*HMACcomputesaHashedMessageAuthenticationCodewiththe
*cryptohashalgorithmasaparameter.
*
*@paramcrypto:thecryptoalgorithm(HmacSHA1,HmacSHA256,
*HmacSHA512)
*@paramkeyBytes:thebytestousefortheHMACkey
*@paramtext:themessageortexttobeauthenticated
*/

M'Raihi,etal.Informational[Page9]
https://tools.ietf.org/html/rfc6238

9/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
privatestaticbyte[]hmac_sha(Stringcrypto,byte[]keyBytes,
byte[]text){
try{
Machmac;
hmac=Mac.getInstance(crypto);
SecretKeySpecmacKey=
newSecretKeySpec(keyBytes,"RAW");
hmac.init(macKey);
returnhmac.doFinal(text);
}catch(GeneralSecurityExceptiongse){
thrownewUndeclaredThrowableException(gse);
}
}
/**
*ThismethodconvertsaHEXstringtoByte[]
*
*@paramhex:theHEXstring
*
*@return:abytearray
*/
privatestaticbyte[]hexStr2Bytes(Stringhex){
//Addingonebytetogettherightconversion
//Valuesstartingwith"0"canbeconverted
byte[]bArray=newBigInteger("10"+hex,16).toByteArray();
//CopyalltheREALbytes,notthe"first"
byte[]ret=newbyte[bArray.length1];
for(inti=0;i<ret.length;i++)
ret[i]=bArray[i+1];
returnret;
}
privatestaticfinalint[]DIGITS_POWER
//012345678
={1,10,100,1000,10000,100000,1000000,10000000,100000000};

M'Raihi,etal.Informational[Page10]
https://tools.ietf.org/html/rfc6238

10/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
/**
*ThismethodgeneratesaTOTPvalueforthegiven
*setofparameters.
*
*@paramkey:thesharedsecret,HEXencoded
*@paramtime:avaluethatreflectsatime
*@paramreturnDigits:numberofdigitstoreturn
*
*@return:anumericStringinbase10thatincludes
*{@linktruncationDigits}digits
*/
publicstaticStringgenerateTOTP(Stringkey,
Stringtime,
StringreturnDigits){
returngenerateTOTP(key,time,returnDigits,"HmacSHA1");
}
/**
*ThismethodgeneratesaTOTPvalueforthegiven
*setofparameters.
*
*@paramkey:thesharedsecret,HEXencoded
*@paramtime:avaluethatreflectsatime
*@paramreturnDigits:numberofdigitstoreturn
*
*@return:anumericStringinbase10thatincludes
*{@linktruncationDigits}digits
*/
publicstaticStringgenerateTOTP256(Stringkey,
Stringtime,
StringreturnDigits){
returngenerateTOTP(key,time,returnDigits,"HmacSHA256");
}

M'Raihi,etal.Informational[Page11]
https://tools.ietf.org/html/rfc6238

11/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
/**
*ThismethodgeneratesaTOTPvalueforthegiven
*setofparameters.
*
*@paramkey:thesharedsecret,HEXencoded
*@paramtime:avaluethatreflectsatime
*@paramreturnDigits:numberofdigitstoreturn
*
*@return:anumericStringinbase10thatincludes
*{@linktruncationDigits}digits
*/
publicstaticStringgenerateTOTP512(Stringkey,
Stringtime,
StringreturnDigits){
returngenerateTOTP(key,time,returnDigits,"HmacSHA512");
}
/**
*ThismethodgeneratesaTOTPvalueforthegiven
*setofparameters.
*
*@paramkey:thesharedsecret,HEXencoded
*@paramtime:avaluethatreflectsatime
*@paramreturnDigits:numberofdigitstoreturn
*@paramcrypto:thecryptofunctiontouse
*
*@return:anumericStringinbase10thatincludes
*{@linktruncationDigits}digits
*/
publicstaticStringgenerateTOTP(Stringkey,
Stringtime,
StringreturnDigits,
Stringcrypto){
intcodeDigits=Integer.decode(returnDigits).intValue();
Stringresult=null;
//Usingthecounter
//First8bytesareforthemovingFactor
//CompliantwithbaseRFC4226(HOTP)
while(time.length()<16)
time="0"+time;
//GettheHEXinaByte[]
byte[]msg=hexStr2Bytes(time);
byte[]k=hexStr2Bytes(key);

M'Raihi,etal.Informational[Page12]
https://tools.ietf.org/html/rfc6238

12/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
byte[]hash=hmac_sha(crypto,k,msg);
//putselectedbytesintoresultint
intoffset=hash[hash.length1]&0xf;
intbinary=
((hash[offset]&0x7f)<<24)|
((hash[offset+1]&0xff)<<16)|
((hash[offset+2]&0xff)<<8)|
(hash[offset+3]&0xff);
intotp=binary%DIGITS_POWER[codeDigits];
result=Integer.toString(otp);
while(result.length()<codeDigits){
result="0"+result;
}
returnresult;
}
publicstaticvoidmain(String[]args){
//SeedforHMACSHA120bytes
Stringseed="3132333435363738393031323334353637383930";
//SeedforHMACSHA25632bytes
Stringseed32="3132333435363738393031323334353637383930"+
"313233343536373839303132";
//SeedforHMACSHA51264bytes
Stringseed64="3132333435363738393031323334353637383930"+
"3132333435363738393031323334353637383930"+
"3132333435363738393031323334353637383930"+
"31323334";
longT0=0;
longX=30;
longtestTime[]={59L,1111111109L,1111111111L,
1234567890L,2000000000L,20000000000L};
Stringsteps="0";
DateFormatdf=newSimpleDateFormat("yyyyMMddHH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));

M'Raihi,etal.Informational[Page13]
https://tools.ietf.org/html/rfc6238

13/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
try{
System.out.println(
"+++"+
"+++");
System.out.println(
"|Time(sec)|Time(UTCformat)"+
"|ValueofT(Hex)|TOTP|Mode|");
System.out.println(
"+++"+
"+++");
for(inti=0;i<testTime.length;i++){
longT=(testTime[i]T0)/X;
steps=Long.toHexString(T).toUpperCase();
while(steps.length()<16)steps="0"+steps;
StringfmtTime=String.format("%1$11s",testTime[i]);
StringutcTime=df.format(newDate(testTime[i]*1000));
System.out.print("|"+fmtTime+"|"+utcTime+
"|"+steps+"|");
System.out.println(generateTOTP(seed,steps,"8",
"HmacSHA1")+"|SHA1|");
System.out.print("|"+fmtTime+"|"+utcTime+
"|"+steps+"|");
System.out.println(generateTOTP(seed32,steps,"8",
"HmacSHA256")+"|SHA256|");
System.out.print("|"+fmtTime+"|"+utcTime+
"|"+steps+"|");
System.out.println(generateTOTP(seed64,steps,"8",
"HmacSHA512")+"|SHA512|");
System.out.println(
"+++"+
"+++");
}
}catch(finalExceptione){
System.out.println("Error:"+e);
}
}
}
<CODEENDS>
AppendixB.TestVectors
ThissectionprovidestestvaluesthatcanbeusedfortheHOTPtime
basedvariantalgorithminteroperabilitytest.

M'Raihi,etal.Informational[Page14]
https://tools.ietf.org/html/rfc6238

14/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
ThetesttokensharedsecretusestheASCIIstringvalue
"12345678901234567890".WithTimeStepX=30,andtheUnixepochas
theinitialvaluetocounttimesteps,whereT0=0,theTOTP
algorithmwilldisplaythefollowingvaluesforspecifiedmodesand
timestamps.
++++++
|Time(sec)|UTCTime|ValueofT(hex)|TOTP|Mode|
++++++
|59|19700101|0000000000000001|94287082|SHA1|
||00:00:59||||
|59|19700101|0000000000000001|46119246|SHA256|
||00:00:59||||
|59|19700101|0000000000000001|90693936|SHA512|
||00:00:59||||
|1111111109|20050318|00000000023523EC|07081804|SHA1|
||01:58:29||||
|1111111109|20050318|00000000023523EC|68084774|SHA256|
||01:58:29||||
|1111111109|20050318|00000000023523EC|25091201|SHA512|
||01:58:29||||
|1111111111|20050318|00000000023523ED|14050471|SHA1|
||01:58:31||||
|1111111111|20050318|00000000023523ED|67062674|SHA256|
||01:58:31||||
|1111111111|20050318|00000000023523ED|99943326|SHA512|
||01:58:31||||
|1234567890|20090213|000000000273EF07|89005924|SHA1|
||23:31:30||||
|1234567890|20090213|000000000273EF07|91819424|SHA256|
||23:31:30||||
|1234567890|20090213|000000000273EF07|93441116|SHA512|
||23:31:30||||
|2000000000|20330518|0000000003F940AA|69279037|SHA1|
||03:33:20||||
|2000000000|20330518|0000000003F940AA|90698825|SHA256|
||03:33:20||||
|2000000000|20330518|0000000003F940AA|38618901|SHA512|
||03:33:20||||
|20000000000|26031011|0000000027BC86AA|65353130|SHA1|
||11:33:20||||
|20000000000|26031011|0000000027BC86AA|77737706|SHA256|
||11:33:20||||
|20000000000|26031011|0000000027BC86AA|47863826|SHA512|
||11:33:20||||
++++++
Table1:TOTPTable

M'Raihi,etal.Informational[Page15]
https://tools.ietf.org/html/rfc6238

15/17

7/4/2016

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

RFC6238HOTPTimeBasedMay2011
Authors'Addresses
DavidM'Raihi
Verisign,Inc.
685E.MiddlefieldRoad
MountainView,CA94043
USA
EMail:davidietf@gmail.com
SalahMachani
DiversinetCorp.
2225SheppardAvenueEast,Suite1801
Toronto,OntarioM2J5C2
Canada
EMail:smachani@diversinet.com
MingliangPei
Symantec
510E.MiddlefieldRoad
MountainView,CA94043
USA
EMail:Mingliang_Pei@symantec.com
JohanRydell
Portwise,Inc.
275HawthorneAve.,Suite119
PaloAlto,CA94301
USA
EMail:johanietf@gmail.com

M'Raihi,etal.Informational[Page16]
https://tools.ietf.org/html/rfc6238

16/17

7/4/2016

https://tools.ietf.org/html/rfc6238

RFC6238TOTP:TimebasedOnetimePasswordAlgorithm

17/17

Vous aimerez peut-être aussi