Java implementation Google Two step verification (Google Authenticator)

Source: Internet
Author: User
Tags base64 string format

Get ready:

A Google two-step verification app, I'm using iOS identity treasure

Information:

1.Google Authenticator principle and Java implementation//main reference

76947962#

2. What is the principle of Google verification (Google Authenticator)?

https://www.zhihu.com/question/20462696

3. Google verification, also known as two-step verification,

Https://www.360shouzhuan.com/android/news/youxi/1632.htm

This is Google two step verification, get key, with authentication,

 PackageCom.rekoo;//Google Authenticator//just from Google two-factor authentication, it is convenient for everyone, the same as with Google a level of security, but we how to use Google Authenticator (two-factor authentication),//here is the Java algorithm, so that everyone can get the public key according to key, directly copy, remember to import the jar package:////Commons-codec-1.8.jar////Junit-4.10.jar//test method:////1, execute the "Gensecret" method in the test code, will generate a key (user is testuser), URL Open is a two-dimensional code image. ////2. Download "Google Authenticator" in your phone. ////3, configure the account in the authenticator, enter the account name (user TestUser in the first step), key (the key generated in the first step), select time based. ////4, run Authcode method will key and the verification code to be tested in (Codes,key), you can know is not the correct secret key! return value Boolean//I'm not going to write about this, because this can be called directly as a util tool.//Importjava.security.InvalidKeyException;Importjava.security.NoSuchAlgorithmException;ImportJava.security.SecureRandom;ImportJavax.crypto.Mac;ImportJavax.crypto.spec.SecretKeySpec;Importorg.apache.commons.codec.binary.Base32;Importorg.apache.commons.codec.binary.Base64; Public classGoogleauthenticator {//taken from Google Pam Docs-we probably don ' t need to mess with these     Public Static Final intSecret_size = 10;  Public Static FinalString SEED = "G8GJEVTBW5OVSV7AVLBDWIHQGLUYNZKFI7IZOF8GWLDVKS2M0QN7VXRS2IM5MDANCWGMCD2RVCZX";  Public Static FinalString random_number_algorithm = "Sha1prng"; intWindow_size = 3;//default 3-max (from Google Docs) up to offset time     Public voidSetwindowsize (ints) {if(S >= 1 && s <= 17) Window_size=s; }     Public StaticBoolean Authcode (string codes, String Savedsecret) {//Enter the code shown on device. Edit this and run it fast before the//Code expires!        LongCode =Long.parselong (codes); Longt =System.currenttimemillis (); Googleauthenticator GA=NewGoogleauthenticator (); Ga.setwindowsize (15);//should give 5 * seconds of grace ...        BooleanR =Ga.check_code (Savedsecret, code, T); returnR; }     Public Staticstring Gensecret (string name) {string Secret=Googleauthenticator.generatesecretkey (); //Googleauthenticator.getqrbarcodeurl ("TestUser", "Testhost", secret);Googleauthenticator.getqrbarcodeurl (name,"Testhost", secret); returnsecret; }     Public StaticString Generatesecretkey () {securerandom SR=NULL; Try{SR=securerandom.getinstance (Random_number_algorithm);            Sr.setseed (Base64.decodebase64 (SEED)); byte[] buffer =sr.generateseed (secret_size); BASE32 codec=NewBase32 (); byte[] Bencodedkey =codec.encode (buffer); String Encodedkey=NewString (Bencodedkey); returnEncodedkey; }Catch(nosuchalgorithmexception e) {//should never occur ... configuration error        }        return NULL; }     Public Staticstring Getqrbarcodeurl (string user, string host, String secret) {string format= "Https://www.google.com/chart?chs=200x200&chld=m%%7c0&cht=qr&chl=otpauth://totp/%[email protected] %s%%3fsecret%%3d%s "; returnString.Format (format, user, host, secret); }     Public BooleanCheck_code (String Secret,LongCodeLongtimemsec) {BASE32 codec=NewBase32 (); byte[] Decodedkey =Codec.decode (Secret); //convert Unix msec time into a second "window"//This was per the TOTP spec (see the RFCs for details)        Longt = (timemsec/1000l)/30L; //Window is used-check codes generated in the near past. //You can use the this value to tune what far you ' re willing to go.         for(inti =-window_size; I <= window_size; ++i) {LongHash; Try{Hash= Verify_code (Decodedkey, T +i); }Catch(Exception e) {//Yes, this is the bad form-but//The exceptions thrown would be rare and a static configuration problemE.printstacktrace (); Throw Newruntimeexception (E.getmessage ()); //return false;            }            if(Hash = =code) {                return true; }        }        //The validation code is invalid.        return false; }    Private Static intVerify_code (byte[] Key,LongTthrowsnosuchalgorithmexception, invalidkeyexception {byte[] data =New byte[8]; LongValue =T;  for(inti = 8; i--> 0; Value >>>= 8) {Data[i]= (byte) value; } secretkeyspec SignKey=NewSecretkeyspec (Key, "HmacSHA1"); Mac Mac= Mac.getinstance ("HmacSHA1");        Mac.init (SignKey); byte[] hash =mac.dofinal (data); intoffset = hash[20-1] & 0xF; //We ' re using a long because Java hasn ' t got unsigned int.        LongTruncatedhash = 0;  for(inti = 0; I < 4; ++i) {Truncatedhash<<= 8; //We is dealing with signed bytes://We just keep the first byte.Truncatedhash |= (Hash[offset + i] & 0xFF); } Truncatedhash&= 0x7FFFFFFF; Truncatedhash%= 1000000; return(int) Truncatedhash; }     Public Static voidMain (string[] args) {String secret= Gensecret ("TestUser");//Get Key System.out.println ("Secret:" +secret); String Key= ""; Boolean Authcode =Authcode (key, secret);//Validationif(Authcode) {System.out.printf ("It's really ...."); }Else{System.out.printf ("False ...."); }    }}

Finally: Dear reader, can I have a bit of powder?

Java implementation Google Two step verification (Google Authenticator)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.