API calls - Encrypted identity authentication

Updated at:

Encrypted identity authentication is a high-security method for calling shared APIs. It uses a signature for identity authentication, which is calculated by an encryption algorithm that uses basic API information and authorized application information. This topic describes how to call an API that uses encrypted identity authentication.

Background information

Authentication: To ensure secure and controlled API use, you must add the following parameters to the HTTP request header. These parameters must be calculated for each request. Data Resource Platform verifies these parameters. Requests that fail verification are considered invalid.

Parameter

Description

Date

The time the request was sent. The date format must be in GMT.

signature

The signature information calculated for the current request.

Content-MD5

The MD5 hash of the request content data.

This can be empty. Calculate the Content-MD5 header only when the request has a body and the body is not in a form format.

Prerequisites

The target API must be configured to use encrypted identity authentication.

Call examples

Calculate a signature using an SDK (Recommended)

Dbus provides a Java SDK that includes the signature calculation method for encrypted identity authentication. By integrating the SDK into your Java application, you can call the API directly without manually calculating the authentication signature. This is the recommended method because it is fast and easy.

  1. Download the Dbus SDK to your computer. If you are using a Windows environment, run the following command in the Command Prompt window to install the signature SDK to your local repository.

    Note

    The Maven environment variable must be configured.

    mvn install:install-file -DgroupId=com.aliyun.dataq.service.dbus -DartifactId=dbus-sdk -Dversion=1.0.3-SNAPSHOT -Dpackaging=jar -Dfile=${path_to_the_installation_package}/dbus-sdk-1.0.3.jar
  2. Add the dependency to the pom.xml file of your Maven project.

    <dependencies>
        <dependency>
            <groupId>com.aliyun.dataq.service.dbus</groupId>
            <artifactId>dbus-sdk</artifactId>
            <version>1.0.3-SNAPSHOT</version>
        </dependency>
    </dependencies>
  3. The following code provides an example of a Java application call. For more information about how to obtain the endpoint, path, AppCode, AppKey, and AppSecret of the target API, see Obtain API call information.

    Note

    The API access path is a combination of the endpoint and the path.

    import com.alibaba.cosmo.remote.httpclient.HttpMethod;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyun.dataq.service.dbus.signature.DaasClient;
    import com.aliyun.dataq.service.dbus.signature.DataQService;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import java.io.File;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Demo {
        public static void main(String[] args) {
            // The address of the target API
            String endpoint = "https://dataq.aliyuncs.com";
            // The path of the target API
            String path = "/yourworkspaceCode/yourAppCode/APIPath";
            // The AppCode, AppKey, and AppSecret of the application that is authorized to call the API or selected when you create your own API
            String appCode = "yourAppCode";
            String appKey = "yourAppKey";
            String appSecret = "yourAppSecret";
       
            DataQService.Builder builder = new DataQService.Builder();
            builder.setPath(path);
            builder.setAppKey(appKey);
            builder.setAppSecret(appSecret);
            builder.setModuleName(appCode);
    
            // Add request header parameters
            Map<String, Object> headerMap = new HashMap<>();
            headerMap.put("Accept", "application/json");
            headerMap.put("Content-Type", "application/json");
            headerMap.put("h1", "");
            headerMap.put("h2", "");
            builder.addHeader(headerMap);
    
            // Add QueryParam parameters
            Map<String, Object> queryParam = new HashMap<>();
            queryParam.put("p1", "");
            queryParam.put("p2", "");
            builder.addQueryParam(queryParam);
    
            // Add RequestBody parameters
            Map<String, Object> map = new HashMap<>();
            map.put("b1", "");
            List<String> values = Arrays.asList("v1");
            map.put("b2", values);
            builder.setRequestBody(new JSONObject(map));
    
            // File upload
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                    .addTextBody("k1","v1")
                    .addTextBody("k2","v2")
                    .addBinaryBody("file", new File("/demo/2602780.txt"),  ContentType.APPLICATION_OCTET_STREAM, "2602780.txt");
            builder.setMultipartEntityBuilder(multipartEntityBuilder);
    
            // Set the request method
            DataQService dataQService = builder.setHttpMethod(HttpMethod.GET).build();
    
            // Initialize the request client
            DaasClient client = new DaasClient(endpoint);
    
            // Send the request
            Object httpResponse = client.invoke(dataQService, 1000000, 30);
            System.out.println(httpResponse);
        }
    }

Calculate a signature manually

If you cannot use the SDK directly or need to initiate a call request using other methods, you can use the following method to manually calculate the signature.

  1. The logic for composing the signature string varies depending on the request method.

    1. The content is calculated as follows.

      # GET
      ${method}\n${path}\n${date}
      # Non-GET
      ${method}\n${path}\n${date}\n${bodyMd5}
      Note

      If the path contains special characters, you must encode them.

    2. Use the AppSecret as the key to encrypt the calculated content with the HmacSHA1 algorithm. Then, perform Base64 encoding on the resulting ciphertext to obtain the final output. For more information about how to obtain the AppSecret, see Obtain API call information.

  2. The following sections provide examples of signature calculation for Java and JavaScript applications.

    • Java application signature calculation.

      import org.apache.commons.codec.binary.Base64;
      import org.apache.commons.codec.binary.Hex;
      import org.apache.commons.lang3.StringUtils;
      import org.apache.commons.lang3.time.FastDateFormat;
      import javax.crypto.Mac;
      import javax.crypto.spec.SecretKeySpec;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.OutputStream;
      import java.net.URLDecoder;
      import java.security.MessageDigest;
      import java.security.NoSuchAlgorithmException;
      import java.text.ParseException;
      import java.util.Arrays;
      import java.util.Date;
      import java.util.Locale;
      import java.util.TimeZone;
      
      public abstract class SignUtils {
      
          public static final String EMPTY_STRING_MD5;
      
          private static FastDateFormat DATE_FORMAT;
      
          static {
              DATE_FORMAT = FastDateFormat
                      .getInstance("E, dd MMM yyyy HH:mm:ss z", TimeZone.getTimeZone("GMT"), Locale.UK);
              try {
                  MessageDigest md = MessageDigest.getInstance("md5");
                  md.update("".getBytes("UTF-8"));
                  EMPTY_STRING_MD5 = Base64.encodeBase64String(md.digest());
              } catch (Exception ex) {
                  throw new IllegalArgumentException(ex);
              }
          }
      
          public static Date parseGmtDate(String date) throws ParseException {
              return DATE_FORMAT.parse(date);
          }
      
          public static String formatGmtDate(Date date) {
              return DATE_FORMAT.format(date);
          }
      
          public static String toMd5(InputStream stream) throws Exception {
              return toMd5(stream, false);
          }
      
          public static String toMd5(InputStream stream, boolean parseEmptyStream) throws Exception {
              try {
                  boolean nocontent = true;
                  MessageDigest md = MessageDigest.getInstance("md5");
      
                  int len = -1;
                  byte[] buf = new byte[1024];
      
                  while ((len = stream.read(buf)) != -1) {
                      nocontent = false;
                      md.update(buf, 0, len);
                  }
      
                  return nocontent ?
                          (parseEmptyStream ? EMPTY_STRING_MD5 : "") :
                          Base64.encodeBase64String(md.digest());
              } finally {
                  stream.close();
              }
          }
      
          public static String toMd5(byte[] content) throws Exception {
              if (content == null || content.length == 0) {
                  return null;
              }
              return Base64.encodeBase64String(MessageDigest.getInstance("md5").digest(content));
          }
      
          public static String toMd5(String content) throws Exception {
              return toMd5(content.getBytes("UTF-8"));
          }
      
          public static String toHmacSHA1(String data, String AppSecret) throws Exception {
              String algorithm = "HmacSHA1";
              SecretKeySpec signingKey = new SecretKeySpec(AppSecret.getBytes("UTF-8"), algorithm);
              Mac mac = Mac.getInstance(algorithm);
              mac.init(signingKey);
              byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
              return Base64.encodeBase64String(rawHmac);
          }
      
          public static String sign4Base(String param, String salt) throws Exception {
              if (StringUtils.isEmpty(param) || StringUtils.isEmpty(salt)) {
                  return null;
              }
      
              String query = URLDecoder.decode(param, "UTF-8");
      
              String[] pStr = query.trim().split("&");
              Arrays.sort(pStr);
      
              StringBuilder buf = new StringBuilder(salt).append(':');
              for (int i = 0; i < pStr.length; ++i) {
                  buf.append(pStr[i]);
                  buf.append("&");
              }
              buf.setCharAt(buf.length() - 1, ':');
              buf.append(salt);
      
              MessageDigest md = MessageDigest.getInstance("SHA-256");
              byte[] bytes = md.digest(buf.toString().getBytes("UTF-8"));
      
              return Hex.encodeHexString(bytes).toLowerCase();
          }
      
          private static String signedString(String method, String url, String date, String contentMd5) {
              HttpMethod hm = HttpMethod.valueOf(method.toUpperCase());
              if (hm == null) {
                  throw new IllegalArgumentException("Unknown Http Method: " + method);
              }
      
              if (hm.needBody && contentMd5 == null) {
                  contentMd5 = "";
              }
              if (contentMd5 == null) {
                  StringBuilder buf = new StringBuilder(method.length() + url.length() + date.length());
                  return buf.append(method).append('\n').append(url).append('\n').append(date).toString();
              }
              StringBuilder buf = new StringBuilder(
                      method.length() + url.length() + date.length() + contentMd5.length());
              return buf.append(method).append('\n').append(url).append('\n').append(date).append('\n')
                      .append(contentMd5).toString();
          }
      
          private static String doSign(String module, String appKey, String appSecret, String signedString)
                  throws Exception {
              String signature = toHmacSHA1(signedString, appSecret);
              StringBuilder buf = new StringBuilder(module.length() + appKey.length() + signature.length() + 2);
              return buf.append(module).append(' ').append(appKey).append(':').append(signature).toString();
          }
      
          public static String originalSign4Dtboost(String appSecret, String method, String url, String gmtDate)
                  throws Exception {
              return originalSign4Dtboost(appSecret, method, url, gmtDate, null);
          }
      
          public static String originalSign4Dtboost(String appSecret, String method, String url, String gmtDate,
                                                    String contentMd5) throws Exception {
              String signedString = signedString(method, url, gmtDate, contentMd5);
              return toHmacSHA1(signedString, appSecret);
          }
      
          public static String sign4Dtboost(String module, String appKey, String appSecret, String method,
                                            String url, String gmtDate) throws Exception {
              return sign4Dtboost(module, appKey, appSecret, method, url, gmtDate, null);
          }
      
          public static String sign4Dtboost(String module, String appKey, String appSecret, String method,
                                            String url, String gmtDate, String contentMd5) throws Exception {
              String signedString = signedString(method, url, gmtDate, contentMd5);
              return doSign(module, appKey, appSecret, signedString);
          }
      
          public static String[] spliteSign4Dtboost(String signature) {
              int moduleIndex = signature.indexOf(' ');
              if ((moduleIndex < 1) || (moduleIndex + 3) == signature.length()) {
                  return null;
              }
              int accessIdIndex = signature.indexOf(':', moduleIndex);
              if ((accessIdIndex < 2) || (accessIdIndex + 1) == signature.length()) {
                  return null;
              }
              return new String[] {signature.substring(0, moduleIndex),
                      signature.substring(moduleIndex + 1, accessIdIndex), signature.substring(accessIdIndex + 1)};
          }
      
          private static String signedString(String method, String accept, String gmtDate, String url,
                                             String contentType, String contentMd5) {
              if (accept == null) {
                  accept = "";
              }
              if (contentType == null) {
                  contentType = "";
              }
              if (contentMd5 == null) {
                  contentMd5 = "";
              }
              method = method.toUpperCase();
      
              StringBuilder buf = new StringBuilder(
                      method.length() + accept.length() + gmtDate.length() + url.length() + contentType.length()
                              + contentMd5.length());
      
              return buf.append(method).append('\n').append(accept).append('\n').append(contentMd5).append('\n')
                      .append(contentType).append('\n').append(gmtDate).append('\n').append(url).toString();
          }
      
          public static String originalSign4Dataplus(String appSecret, String method, String accept, String gmtDate,
                                                     String url) throws Exception {
              return originalSign4Dataplus(appSecret, method, accept, gmtDate, url, null, null);
          }
      
          public static String originalSign4Dataplus(String appSecret, String method, String accept, String gmtDate,
                                                     String url, String contentType, String contentMd5) throws Exception {
              String signedString = signedString(method, accept, gmtDate, url, contentType, contentMd5);
              return toHmacSHA1(signedString, appSecret);
          }
      
          @Deprecated public static String sign4Datapuls(String module, String appKey, String appSecret,
                                                         String method, String accept, String gmtDate, String url) throws Exception {
              return sign4Dataplus(module, appKey, appSecret, method, accept, gmtDate, url);
          }
      
          public static String sign4Dataplus(String module, String appKey, String appSecret, String method,
                                             String accept, String gmtDate, String url) throws Exception {
              return sign4Dataplus(module, appKey, appSecret, method, accept, gmtDate, url, null, null);
          }
      
          @Deprecated public static String sign4Datapuls(String module, String appKey, String appSecret,
                                                         String method, String accept, String gmtDate, String url, String contentType, String contentMd5)
                  throws Exception {
              return sign4Datapuls(module, appKey, appSecret, method, accept, gmtDate, url, contentType,
                      contentMd5);
          }
      
          public static String sign4Dataplus(String module, String appKey, String appSecret, String method,
                                             String accept, String gmtDate, String url, String contentType, String contentMd5)
                  throws Exception {
              String signedString = signedString(method, accept, gmtDate, url, contentType, contentMd5);
              return doSign(module, appKey, appSecret, signedString);
          }
      
          public static String[] spliteSign4Dataplus(String signature) {
              return spliteSign4Dtboost(signature);
          }
      
          enum HttpMethod {
              /**
               * HTTP METHOD
               */
              GET(false), POST(true), PUT(true), DELETE(false), PATCH(true), HEAD(false), OPTIONS(false), TRACE(
                      false);
      
              private final boolean needBody;
      
              private HttpMethod(boolean needBody) {
                  this.needBody = needBody;
              }
          }
      
          public static final class Md5CalculatedOutputStream extends OutputStream {
      
              private boolean nocontent = true;
      
              private final MessageDigest md;
              private final boolean parseEmptyStream;
      
              public Md5CalculatedOutputStream() throws NoSuchAlgorithmException {
                  this(false);
              }
      
              public Md5CalculatedOutputStream(boolean parseEmptyStream) throws NoSuchAlgorithmException {
                  md = MessageDigest.getInstance("md5");
                  this.parseEmptyStream = parseEmptyStream;
              }
      
              @Override public void write(int b) throws IOException {
                  if (nocontent) {
                      nocontent = false;
                  }
                  md.update((byte) b);
              }
      
              @Override public void write(byte b[]) throws IOException {
                  if (b == null) {
                      throw new NullPointerException();
                  } else if (b.length != 0) {
                      if (nocontent) {
                          nocontent = false;
                      }
                      md.update(b);
                  }
      
              }
      
              @Override public void write(byte b[], int off, int len) throws IOException {
                  if (b == null) {
                      throw new NullPointerException();
                  } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len)
                          < 0)) {
                      throw new IndexOutOfBoundsException();
                  } else if (len != 0) {
                      if (nocontent) {
                          nocontent = false;
                      }
                      md.update(b, off, len);
                  }
              }
      
              public String toMd5() {
                  if (nocontent) {
                      return parseEmptyStream ? EMPTY_STRING_MD5 : "";
                  }
                  return Base64.encodeBase64String(md.digest());
              }
          }
      }
    • JavaScript application signature calculation.

      For more information about how to obtain the AppKey and AppSecret, see Obtain API call information.

      function sign(url, method, headers, appKey, appSecret, body) {
            const appSecret = appSecret;
            const md5 = function (buffer) {
              return crypto.createHash('md5').update(buffer).digest('base64');
            };
            const sha1 = function (stringToSign, appSecret) {
              return crypto.createHmac('sha1', AppSecret).update(stringToSign).digest().toString('base64');
            };
            body = body || {};
            let bodymd5 = '';
            if (body && _.size(body) && ['POST', 'PUT', 'PATCH'].indexOf(method.toUpperCase()) >= 0) {
              bodymd5 = crypto.createHash('md5').update(Buffer.from(JSON.stringify(body))).digest('base64');
            }
            let stringToSign = method + '\n' + Url.parse(url).path + '\n' + headers.date;
            if (bodymd5) {
              stringToSign = stringToSign + '\n' + bodymd5;
            }
            let signature = sha1(stringToSign, appSecret);
            let authHeader = `common-user-ak-v1 ${appKey}:${signature}`;
            return authHeader;
        }