Skip to content

TOTP (RFC 6238) and HOTP (RFC 4226) reference implementations and more.

License

Notifications You must be signed in to change notification settings

oliveryasuna/crypto

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Crypto

Time-Based One-Time Password (RFC 6238) and HMAC-Based One-Time Password (RFC 4226) reference implementations and more.

Getting Started

TOTP generation

// Passwords will be 6 digits, change every 30 seconds, and are computed with SHA-1.
TOTP totp = new TOTP(6, Duration.ofSeconds(30L), Keys.generate("HmacSHA1", 160), SHA1.getInstance());

totp.compute(Instant.now());
// OR
totp.compute(Instant.now().toEpochMillis());

HOTP generation

// Passwords will be 6 digits and are computed with SHA-1.
HOTP hotp = new HOTP(6, Keys.generate("HmacSHA1", 160), SHA1.getInstance());

hotp.compute(0L);

HMAC signing

byte[] input = "Hello, World!".getBytes();

// Create an HMAC instance.
HMAC hmac = new HMAC(Keys.generate("AES"), SHA1.getInstance());

// Sign the input.
byte[] tag = hmac.sign(input);

...

// Verify the input later.
boolean valid = hmac.verify(input, tag);

Alternatively, you can use JceMAC, which wraps JCE's Mac:

JceMac hmac = new JceMac(Keys.generate("AES"), "HmacSHA1");

Hashing

Classes: MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, SHA512t224, SHA512t256.

byte[] input = "Hello, World!".getBytes();

// Hash the input using SHA-1.
byte[] hash = SHA1.getInstance().compute(input);

Utility classes' methods

Keys:

  • byte[] generate(String algorithm, SecureRandom secureRandom) – Generates a key, specifying the algorithm and SecureRandom.
  • byte[] generate(String algorithm, int keySize) – Generates a key, specifying the algorithm and key size in bytes.
  • byte[] generate(String algorithm) – Generates a key, specifying the algorithm.

Bytes:

  • byte[] concatenate(byte[] array, byte[]... arrays) – Concatenates n-arrays.
  • byte[] xor(byte[] array1, byte[] array2) – XOR operation on two arrays.
  • byte[] toHex(byte[] bytes) – Converts bytes to hexadecimal bytes.

License

This code is under the BSD 3-Clause.

Sponsoring

If you like my work and want to support it, please consider sponsoring me. Your support helps me make the time to code great things!

About

TOTP (RFC 6238) and HOTP (RFC 4226) reference implementations and more.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Languages