Updated on 1/13/2017
BaaS Guide
Signature generation in Java
Direct link to topic in this publication:

Signature generation

Signature is generated by signing some header fields. The fields Method, Content-Type and the BOS name are joined with a line-feed character (0x10). The concatenated string is hashed using the secret.  The hashed value is encoded as a character string using Base64 encoding. The algorithm is provided in Java below.


import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

 

public class Signer {

  private SecretKeySpec signingKey = null;

  private Mac mac = null;

  private SimpleDateFormat df;

  private String signDate;

 

  public Signer(String secret)

    throws NoSuchAlgorithmException,

      UnsupportedEncodingException,

      InvalidKeyException{

    mac = Mac.getInstance("HmacSHA1");

    byte[] keyBytes = secret.getBytes("UTF8");

signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    mac.init(signingKey);    

  }

 

  public String sign(String method,

    String mime,String bosName)

      throws IllegalStateException,

        UnsupportedEncodingException{

    StringBuffer buf = new StringBuffer();

    buf.append(method).append("\n");

    buf.append(mime).append("\n");

    buf.append(bosName);

    return sign(buf.toString());

  }

 

 

 

private String sign(String data)

    throws IllegalStateException,

      UnsupportedEncodingException {

byte[] signBytes = mac.doFinal(data.getBytes("UTF8"));

    String signature =Base64.encode(signBytes);

    return signature;

  }

}