RESTful API

Ciphering Data

Sometimes using this REST API we find ourselves in situations where we need to use some kind of encryption in order to pass through some text parameters that could contain special characters and may cause data loss or maybe to obfuscate text to make it more secure

To avoid this kind of situations we use use Base64 or SHA256.

All classes used here are present in Java 1.8. No additional libraries are required

We can easily transform a text block into a Base64 String in java by doing

new String(Base64.getUrlEncoder().encode(data), StandardCharsets.UTF_8);

Also, we can decode a Base64 String into regular text by doing:

new String(Base64.getUrlDecoder().decode(data.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);

In java it's pretty easy to cipher using SHA256, the following method uses no libraries to achieve that goal

private static String signHmacSHA256(String message, byte[] key) {
	try {
		SecretKey signingKey = new SecretKeySpec(key, "HMACSHA256");
		Mac mac = Mac.getInstance("HMACSHA256");
		mac.init(signingKey);
		byte[] digest = mac.doFinal(message.getBytes("UTF-8"));
		char[] hexadecimals = new char[digest.length * 2];
		for (int i = 0; i < digest.length; ++i) {
			for (int j = 0; j < 2; ++j) {
				int value = (digest[i] >> (4 - 4 * j)) & 0xf;
				char base = (value < 10) ? ('0') : ('a' - 10);
				hexadecimals[i * 2 + j] = (char) (base + value);
			}
		}
		return new String(hexadecimals);
	} catch (Exception e) {
		e.printStackTrace();
		return message;
	}
}

In java it's possible to cipher using HmacSHA512, the following method uses the following libraries to achieve that goal

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

An example

private String sign(String algorithm, String input, byte[] key) throws Exception {
	    Mac mac = Mac.getInstance(algorithm);
	    mac.init(new SecretKeySpec(key, algorithm));
	    return DatatypeConverter.printHexBinary(mac.doFinal(input.getBytes("UTF-8"))).toLowerCase();
	}