Giter VIP home page Giter VIP logo

two-factor-auth's Introduction

Two (2) Factor Authentication (2FA) Java Code

2 Factor Authentication (2FA) Java code which used the Time-based One-time Password (TOTP) algorithm. You can use this code with the Google Authenticator mobile app or the Authy mobile or browser app.

To get this to work you:

  1. Use generateBase32Secret() to generate a secret key in base-32 format for the user. For example: "NY4A5CPJZ46LXZCP"
  2. Store the secret key in the database associated with the user account.
  3. Display the QR image URL returned by qrImageUrl(...) to the user. Here's a sample which uses GoogleAPIs:
    Sample QR Image
  4. User uses the image to load the secret key into his authenticator application.

Whenever the user logs in:

  1. The user enters the number from the authenticator application into the login form on the web server.
  2. The web server reads the secret associated with the user account from the database.
  3. The server compares the user input with the output from generateCurrentNumberString(...).
  4. If they are equal then the user is allowed to log in.

For more details, see the example program.

Maven Configuration

<dependencies>
	<dependency>
		<groupId>com.j256.two-factor-auth</groupId>
		<artifactId>two-factor-auth</artifactId>
		<version>1.3</version>
	</dependency>
</dependencies>

ChangeLog Release Notes

See the ChangeLog.txt file.

two-factor-auth's People

Contributors

dependabot[bot] avatar j256 avatar wfhartford avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

two-factor-auth's Issues

Compatibility with hardware devices instead of auth apps?

I am still busy researching this and so far I am not sure if I can buy a token device like a yubi-key or rsa-token-id or anything else and use the secret of that device for that specific user instead of relying on the one generated by generateBase32Secret() ?

I'm looking to add 2FA to a java-based web app and the option to use i.e. Google Auth or hardware tokens for different users.

Google's QR API is dead

Use https://api.qrserver.com/v1/create-qr-code/?size=200x200&data= + generateOtpAuthUrl() instead of qrImageUrl()

code is not validating

i have implemented this code in my android application qr generation and scanning is okay but i am unable to validate code generated but google authenticator app validateCurrentNumber() function always returns false. i also check code of 6 digits which always return different value from google authenticator app. please help and guide me how can validate otp. thanks in advance

License?

Would you like to license your code under an open source license?

"Key not recognized" in Google Authenticator app

Hi,

Not sure what am i doing wrong or missing...could be that I don't fully understand what the value of the key should be..my code:
String base32Secret = TimeBasedOneTimePasswordUtil.generateBase32Secret();
String imageUrl = TimeBasedOneTimePasswordUtil.qrImageUrl("[email protected]",base32Secret);
System.out.println(imageUrl);

I click on the URL...and a QR is displayed, and when I scan it with GoogleAuthenticator, I get the error "Key not recognized"..
"[email protected]" is the email that i have in my google authenticator...

Thx!

License

Can I use this for personal or commercial projects? What's the license?

Custom QR Image Dimensions

Parameterize the dimensions so that the size can be customized.

//    200x200 or 400x400
public static String qrImageUrl(String keyId, String secret, String dimension) {
    StringBuilder sb = new StringBuilder(128);
    sb.append("https://chart.googleapis.com/chart?chs="+dimension+"&cht=qr&chl="+dimension+"&chld=M|0&cht=qr&chl=");
		addOtpAuthPart(keyId, secret, sb);
    return sb.toString();
}

Invalid base-32 character: _

secret = SECRET_SHOWN_BY_BITSKINS
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Invalid base-32 character: _
at com.j256.twofactorauth.TimeBasedOneTimePasswordUtil.decodeBase32(TimeBasedOneTimePasswordUtil.java:307)

Use with TOTP systems that generate Hex secrets

Some TOTP systems will generate Hex secrets. This project still works with them. You just need to replace decodeBase32 with:

static byte[] decodeHexToBase32(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

And it works great! 🙂

An example hex secret would look like: 1234567890abcdef1234567890abcdef12345678

generateCurrentNumberString cannot match with the authenticator's code

Hi,
Thank you for the insights!
I was playing around the code, and I noticed that when testing the Example program, the code been generated by generateCurrentNumberString does not match with the code provided by Authenticator even at the first time(i know the code would change), but even for the fist appeared code in Authenticator cannot matched with the output, do you possibly know the reason?

Separate otpauth portion of QR Url

This would allow using another QR code generator, including a JS solution.

/**
 * Return the otpauth part of the QR image. This can be used to generate the QR code within this app or outside
 * (e.g. JS generator)
 *
 * @param keyId
 *            Name of the key that you want to show up in the users authentication application. Should already be
 *            URL encoded.
 * @param secret
 *            Secret string that will be used when generating the current number.
 */
public static String otpauthUrl(String keyId, String secret) {
	StringBuilder sb = new StringBuilder(128);
	sb.append("otpauth://totp/").append(keyId).append("%3Fsecret%3D").append(secret);
	return sb.toString();
}

qrImageUrl invalid for google authenticator

great lib, slight issue with the Url generated, is not valid for google authenticator, working sample code below

public static String qrImageUrl(String keyId, String secret) {
    StringBuilder sb = new StringBuilder(128);
    sb.append("https://chart.googleapis.com/chart?")
            .append("chs=200x200&")
            .append("cht=qr&")
            .append("chld=M|0&")
            .append("chl=")
            .append("otpauth://totp/")
            .append(keyId)
            .append("?secret=")
            .append(secret);
    return sb.toString();
}

Use generateBase32Secret()

Use generateBase32Secret() to generate a secret key in base-32 format for the user. For example: "NY4A5CPJZ46LXZCP"

How to use this for frase:
"SECRET_SHOWN_BY_BITSKINS" ?

Auth keys are invalid after server restart

The keys work fine for any period of time after generating, as long as the server continues to run.

Is there some link between validation and the server that gets stored in cache, and wiped upon restart? Not doing anything custom, just generating QR codes and keys, scanning them with Google Authenticator, and using the validation engine built in. It works 100% of the time right up until a server restart. The secret is stored securely, regardless of what's going on, and it doesn't change when rebooting or anything like that.

Is there a step I'm missing that's causing this issue?

I know the great solution would be never dropping the server, haha, but we can't have our users set up auth again every time the server needs to be updated or rebooted.

Reproducing:

  1. Generate new secret
  2. Add secret to google auth with QR code scanner
  3. Test google key with auth system 👍
  4. Restart server
  5. Test google key with auth system again (failure 👎 )

Suggestion to the error message as well:

"Unable to invoke Cipher due to bad padding" might make some sense for the developer of the library, but it gives no indication to an end user of the library that the key they're using is invalid. Nobody I've worked with had any clue what it meant, and it was only after troubleshooting another issue that we came to see it as "The auth key doesn't match the secret"

windowMillis setting is not correct

in function validateCurrentNumber(String base32Secret, int authNumber, int windowMillis, long timeMillis,
int timeStepSeconds) throws GeneralSecurityException

for (long millis = from; millis <= to; millis += timeStepMillis) {

should be updated to

for (long millis = from; millis <= to; millis += 1000) {

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.