Java sample code for the signature calculation

 

 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;  // JDK 1.8 only - older versions may need to use Apache Commons or similar.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CommandSigner {
	// Note: Generally, you should store your private key someplace safe and read them into your code
	private static String keyString = "YOUR_PRIVATE_KEY";
	private static String commandString = "COMMAND_ITEM_TO_SIGN";
	// This variable stores the binary key, which is computed from the string (Base64) key
	private static byte[] key;
	public static void main(String[] args) throws IOException,
			InvalidKeyException, NoSuchAlgorithmException {
		CommandSigner signer = new CommandSigner(keyString);
		String request = signer.signRequest(commandString);
		System.out.println(request);
	}
	public CommandSigner(String keyString) throws IOException {
	// Convert the key from 'web safe' base 64 to binary
		keyString = keyString.replace('-', '+');
		keyString = keyString.replace('_', '/');
		System.out.println("Key: " + keyString);
		// Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.
		this.key = Base64.getDecoder().decode(keyString);
	}
	public String signRequest(String com) throws NoSuchAlgorithmException,
			InvalidKeyException, UnsupportedEncodingException {
		// Retrieve the proper URL components to sign
		String resource = com;
		// Get an HMAC-SHA1 signing key from the raw key bytes
		SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");
		// Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key
		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(sha1Key);
		// compute the binary signature for the request
		byte[] sigBytes = mac.doFinal(resource.getBytes());
		// base 64 encode the binary signature
		// Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.
		String signature = Base64.getEncoder().encodeToString(sigBytes);
		// convert the signature to 'web safe' base 64
		signature = signature.replace('+', '-');
		signature = signature.replace('/', '_');
		return signature;
	}
}
Terms Of Use | Privacy Statement | Company info
  • © Cedac Sistemi srl
  • Head office: Via Toscana, 3 40035 Castiglione dei Pepoli (Italy) Tel.: +39 0534-93811 Fax: +39 0534-93899
  • Branch office: Via del Lavoro, 47 40033 Casalecchio di Reno (Italy)
  • Branch office: Via Parini, 1 40033 Casalecchio di Reno (Italy)
  • Share capital Euro 26,000.00 - Company Register of Bologna / VAT no / fiscal code 01695261204