Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.4 kB
1
Indexable
Never
    public static String generateOTP(String key, String counter, int returnDigits, String crypto) {
        String result = null;
        byte[] hash;
        
        System.out.println("counter: " + counter);
        
        // Using the counter
        // First 8 bytes are for the movingFactor
        while (counter.length() < 16) {
            counter = "0" + counter;
        }

        // Get the HEX in a Byte[]
        byte[] msg = hexStr2Bytes(counter);
        
        System.out.println("msg: "+ Arrays.toString(msg));

        // Adding one byte to get the right conversion
        // byte[] k = hexStr2Bytes(key);
        byte[] k = key.getBytes();

        hash = hmac_sha1(crypto, k, msg);
        
         System.out.println("hash = " + Arrays.toString(hash));

        // put selected bytes into result int
        int offset = hash[hash.length - 1] & 0xf;
        
        System.out.println("offset = " + offset);

        int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8)
                | (hash[offset + 3] & 0xff);
        
        System.out.println("binary = " + binary);

        int otp = binary % DIGITS_POWER[returnDigits];
        
        System.out.println("binary % DIGITS_POWER[returnDigits] = " + otp);

        result = Integer.toString(otp);

        while (result.length() < returnDigits) {
            result = "0" + result;
        }
        return result;
    }

    public static byte[] hmac_sha1(String crypto, byte[] keyBytes, byte[] text) {
        byte[] value;

        try {
            Mac hmac = Mac.getInstance(crypto);
            SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");

            hmac.init(macKey);

            value = hmac.doFinal(text);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return value;
    }

    public static byte[] hexStr2Bytes(String hex) {
        // Adding one byte to get the right conversion
        // values starting with "0" can be converted
        byte[] bArray = new BigInteger("10" + hex, 16).toByteArray();

        // Copy all the REAL bytes, not the "first"
        byte[] ret = new byte[bArray.length - 1];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = bArray[i + 1];
        }
        return ret;
    }