Back to The tech awesomeness
Table of contents
Java chapters

The article for today.

Somewhere in between creating that article, I have purchased OTP Auth client authenticator.

Then the following code, using the code from https://github.com/jchambers/ and https://www.programcreek.com, I added one more one time password authenticator. And it is using the apache commons library as well as java and javax ones.

It uses the time for the dynamic type of the password.

In the dynamic password it formula is similar to:


user_passwordFORMULASTARTfunctionofhashfordatetimeFORMULAEND

FORMULASTARTfunctionofhashfordatetimeFORMULAENDuser_password

and alike.

public class OneMoreOTPAuth {
    public static void main(final String[] args) 
            throws NoSuchAlgorithmException, InvalidKeyException {
        
        String secret = "1111 2222 3333 4444 5555 6666 7777 8888";
        //secret = secret.replaceAll("\\s","");
        //System.out.println("getOneTimePassword " + getOneTimePasswordAlgorithm1(
          //          secret, 6));
        System.out.println("getOneTimePassword " + getOneTimePasswordAlgorithm2(
                    secret, 6));
        
        secret = "1111222233334444";
        //System.out.println("getOneTimePassword " + getOneTimePasswordAlgorithm1(
          //          secret, 6));
        System.out.println("getOneTimePassword " + getOneTimePasswordAlgorithm2(
                    secret, 6));
        
        secret = "11112222333344445555666677778888";
        //System.out.println("getOneTimePassword " + getOneTimePasswordAlgorithm1(
          //          secret, 6));
        System.out.println("getOneTimePassword " + getOneTimePasswordAlgorithm2(
                    secret, 6));
    }
    public static int getOneTimePasswordAlgorithm1(String secret,
            int lengthToken)
            throws NoSuchAlgorithmException,InvalidKeyException {
        final TimeBasedOneTimePasswordGenerator totp =
                    new TimeBasedOneTimePasswordGenerator(
                            //TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP,
                            Duration.ofSeconds(60),
                            6,
                            TimeBasedOneTimePasswordGenerator
                                    //.TOTP_ALGORITHM_HMAC_SHA512
                                    .TOTP_ALGORITHM_HMAC_SHA1
                    );
            Key key;
            // SHA-1 and SHA-256 prefer 64-byte (512-bit) keys; 
            // SHA512 prefers 128-byte (1024-bit) keys
            key =
                new SecretKeySpec(secret
                        //.getBytes(StandardCharsets.US_ASCII), "RAW");
                        .getBytes(StandardCharsets.UTF_8), "RAW");

            final Instant now = Instant.now();
            final Instant later = now.plus(totp.getTimeStep());
            int result = totp.generateOneTimePassword(key, now);
            System.out.format("Current password: %06d\n", 
                    result);
            System.out.format("Future password:  %06d\n", 
                    totp.generateOneTimePassword(key, later));
            
            return result;
    }
    
    public static long getOneTimePasswordAlgorithm2(String secret, int lengthToken) {
    Base32 codec = new Base32();
    byte[] data = new byte[8];
    long value = (new Date().getTime()) / TimeUnit.SECONDS.toMillis(30);
    for (int i = 8; i-- > 0; value >>>= 8) {
        data[i] = (byte) value;
    }
    SecretKeySpec signKey = new SecretKeySpec(
                codec.decode(
                        //secretKey
                        secret
                ), "HmacSHA1");
    try {
        Mac mac = Mac.getInstance(
                        "HmacSHA1"
                );
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;
        long truncatedHash = 0;
        for (int i = 0; i < 4; ++i) {
            truncatedHash <<= 8;
            truncatedHash |= (hash[offset + i] & 0xFF);
        }
        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000 * 1000;
        return truncatedHash;
    } catch (IllegalStateException | InvalidKeyException
                | NoSuchAlgorithmException e) {
        Logger.getLogger(OneMoreOTPAuth
                            .class.getName()).log(Level.SEVERE, null, e);
        return 0;
    }
    }
}

java --class-path .:/Users/user/one-more-one-time-password-client-authenticator/target/one-more-one-time-password-client-authenticator-1.0.jar:/Users/user/.m2/repository/commons-codec/commons-codec/version/commons-codec-version.jar info.ideasmatter.OneMoreOTPAuth

During testing at least it is working with some Google autentication services.

It is not including the hiding of secret feature, while the client authentication application, which I have purchased includes it.

However, if someone reveals the secret, it is still a subject to change in that case. And still it is only one revelation of the whole dynamic password.

The update from 2020-07-17.

Also one time token is possible not only for passwords, tokens and also for logins, other identifiers.

Both two ones are possible for merging, however then such solo one time unit for supply after generation is possible only from one source or by one algorithm.

For example, password can be for instance in some form from these ones from web site and one time login can be in some text form after generation via email via link.

When such ones are after merging, it then is in one form via one source.

And other direction of merging as well: the amount of such credentials as login, other identifiers, password, token can be more than two, in more than two forms via more than two sources respectively.

Оновлення від 2022-01-02.

The update from 2022-01-02.

Одноразові паролі для прийняття транзакцій з інших пристроїв ВСЕРЕДИНІ тих пристроїв навіть у безпечних додатках чи подібних у поєднанні до якихось інших об'єктів які й необов'язково пристрої було б гарним, однак це відчинило б вгадування віддалено таким чином злами таким чином навіть злами масово якщо з декількох пристроїв які бувають й віртуальні. Хоча і існують ситуації коли це сумісне тож це вибірково і щодо користувачів і щодо користувачок.

One time passwords for accepting transactions from other devices INSIDE those devices even in secure apps or alike in connection with some other objects which are not necesarilly devices would be nice to have, however it would open guessing remotely therefore hijacks therefore even hijacks with bruteforce if from several devices which are not only not virtual ones. Eventhough there are cases when it is suitable thus optional and up to the user.

Оновлення від 2022-06-17.

The update from 2022-06-17.

Така табличка.


                        
                                                                         до;location       через 2FA та інших через ППІ чи вручну;through 2FA and others through API or manually
    SSO;ЄВ
        миттєвий; simultaneous
        немиттєвий; non simultaneous
            through password manager
            через програму для паролів
            through browser; через ППіНТВСуІ
    ЄВи
        миттєвий;simultaneous
            through browser; через ППіНТВСуІ
                через приватний режим; through Private mode
                    принаймні для реп'яшків
                    якщо не для Application storage і інших
        немиттєвий; non simultaneous

http://thetechawesomeness.ideasmatter.info/table-chapters.html;28.

http://thetechawesomeness.ideasmatter.info/table-chapters.html;1.

При розробці такого у деяких ІСР навіть принаймні двома способами досі простіше додати не той символ чи декілька ніж додати деякий інформаційний вірус.

При тому що останні шкодять видимими чи невидимими але вони також і ймовірно вказують на якусь помилку достатньо періодично. Перші ж вказують на вирішену абстрагувальницьку проблему як одним способом про яку було достатньо описано цими веб сторінками принаймні з двох.

Оновлення від 2022-06-19.

The update from 2022-06-19.

2022-06-19. http://thetechawesomeness.ideasmatter.info/index.html