How to create Token in Java


How to create Token in Java

In this article, we will show you a few ways to create/generate a unique token in Java. Creating a unique token is totally depends on the logic and numbers of parameters used. This is the simplest way to create a unique token.

In this example, we have used a combination of following to generate a unique token:

UUID.randomUUID() – return randomly generated UUID.

Instant.now().toEpochMilli() – return the current timestamp in milliseconds.

SecureRandom().nextBytes(bytes) – generates a user-specified number of random bytes.

Base64.getUrlEncoder().encodeToString(bytes) – encodes the specified byte array into a String using the Base64 encoding scheme.

1. Java 8 Supplier

We can use the Supplier functional interface to get a unique token and Stream API for looping it 10 times.

GenerateToken.java
package org.websparrow;

import java.time.Instant;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class GenerateToken {

	public static void main(String[] args) {

		Supplier<String> tokenSupplier = () -> {

			StringBuilder token = new StringBuilder();
			long currentTimeInMilisecond = Instant.now().toEpochMilli();
			return token.append(currentTimeInMilisecond).append("-")
					.append(UUID.randomUUID().toString()).toString();
		};

		Stream.generate(tokenSupplier).limit(10).forEach(System.out::println);

	}
}

Output

1591457374665-d5eff25f-b083-41c3-a90d-a89adcc45043
1591457374808-94eec674-de30-4515-97a0-2f8e70f21118
1591457374808-9ce8579f-3531-4c45-952a-63d8c9bfe96d
1591457374808-8efc21a6-b3f7-40fa-a5ad-57b8a9ad6f09
1591457374808-ca2ed5be-d873-4d33-a6d7-ab67949024a7
1591457374808-1f1e3d4b-ff4f-484c-a5b0-2713a0b4450c
1591457374808-d2382fdd-7e90-4ba3-bf7c-be1355464f5b
1591457374808-b4d4d831-bf99-4822-a259-5d557bdcebfd
1591457374808-4d1f0635-a663-432b-aff3-4805e6e0eec5
1591457374808-59cfe84f-034f-44dd-b82a-e5700b7e9fbb

2. Java 8 Base64

We can also use the SecureRandom class to generate random bytes and encode these bytes to String using  Java 8 Base64 encoder utility class.

GenerateToken2.java
package org.websparrow;

import java.security.SecureRandom;
import java.util.Base64;

public class GenerateToken2 {
	private static final SecureRandom secureRandom = new SecureRandom();
	private static final Base64.Encoder base64Encoder = Base64.getUrlEncoder();

	public static void main(String[] args) {

		for (int i = 1; i <= 10; i++) {
			System.out.println(getToken());
		}
	}

	public static String getToken() {
		byte[] randomBytes = new byte[32];
		secureRandom.nextBytes(randomBytes);
		return base64Encoder.encodeToString(randomBytes);
	}
}

Output

T50-WApPit4rVLNiBuprprIStoldwLosFKgMsZBFoI0=
zB83ukWLeEy7ibMDSxtyjWJ60PXOYwo6l1SU22WCJX8=
gjnqF1fgNIQZ2ACzeCo7vT-op_MSEaAaAdJKvrXhoUo=
EAqUvsn7EF1PCQaTIvwi3moedfKfUygPA7kVfAVtUcI=
w3SQAO6hFm0ZiU7Qtxr0Fr7gg_DEQPcfq0nB8vcKsZE=
E2Uny9Iz-mUDDaUTTTjFnRh1GbUNbTjTwJUsTR1cd7g=
pbl3WmGiAW3z39jPfOOpvqMZGue6TPidqOy_v2V5cG0=
KFifijdPBlTiiZJ0DFry31_HWAn0_CJaiHgntDG6ZrI=
edR0uYppxbxfklHd-hxntsHo9WrR_7Zshgkgh5wk7Mk=
ec7N8NTAY8Z_p-C4_3S82CfJmCTFGMwiUa3oNTyPak4=

3. Java Evergreen

If your JDK version is less than 1.8, you can use the evergreen way of Java.

GenerateToken3.java
package org.websparrow;

import java.time.Instant;
import java.util.UUID;

public class GenerateToken3 {

	public static void main(String[] args) {

		for (int i = 1; i <= 10; i++) {
			System.out.println(getToken());
		}
	}

	public static String getToken() {
		StringBuilder token = new StringBuilder();
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		long currentTimeInMilisecond = timestamp.getTime();
		return token.append(currentTimeInMilisecond).append("-")
				.append(UUID.randomUUID().toString()).toString();
	}
}

Output

1591630301244-cb2b8ec9-ed8f-45fe-95f8-8817889b094e
1591630301405-42aaa902-75d2-4aea-b252-d2eb51ffc571
1591630301405-bb57199b-05df-4795-af29-6a79ab47f881
1591630301406-6df11f73-2d67-4469-a28d-16ded9e56238
1591630301406-96dc312c-53f8-471d-80a6-31cf31d89a57
1591630301406-12ac2ac4-27bd-4db1-81a6-6f4ad575324f
1591630301406-7eaecf07-b3ef-4a0f-bdf8-cdd7186e0d0a
1591630301406-2782462f-980d-464a-bbeb-4eee0fe486d6
1591630301406-43e2dc54-11d6-4aef-a2de-c8558f397130
1591630301406-dc21d1ac-20a8-45ba-8bff-c6ad9501e5f7

Reference

  1. Java 8 – Generating One Time Password (OTP)
  2. Java 8 Base64 Encoding and Decoding Example
  3. How to generate secure random number in Java
  4. Class UUID
  5. Class Instant

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.