Hướng dẫn về chữ ký số

Ký yêu cầu của bạn bằng khoá API

Tuỳ thuộc vào mức sử dụng của bạn, bạn có thể phải dùng chữ ký số (ngoài khoá API) để xác thực các yêu cầu. Để biết thêm thông tin, hãy xem các bài viết sau:

Cách hoạt động của chữ ký số

Chữ ký số sử dụng khoá bí mật ký URL. Khoá này có trong Cloud Console. Khoá bí mật này là một khoá riêng tư chỉ được chia sẻ giữa bạn và Google, đồng thời là khoá duy nhất cho dự án của bạn.

Quy trình ký sử dụng một thuật toán mã hoá để kết hợp URL và khoá bí mật dùng chung của bạn. Chữ ký duy nhất thu được cho phép các máy chủ của Google xác minh rằng mọi trang web tạo yêu cầu bằng khoá API của bạn đều được phép làm như vậy.

Hạn chế các yêu cầu chưa ký

Để đảm bảo khoá API của bạn chỉ chấp nhận các yêu cầu đã ký, hãy làm như sau:

  1. Chuyển đến trang Hạn mức của Google Maps Platform trong Cloud Console.
  2. Trong danh sách thả xuống dự án, hãy chọn dự án mà bạn đã sử dụng khi tạo khoá API cho ứng dụng hoặc trang web của mình.
  3. Trong danh sách thả xuống API, hãy chọn Maps Static API hoặc Street View Static API.
  4. Mở rộng mục Unsigned requests (Yêu cầu chưa ký).
  5. Trong bảng Tên hạn mức, hãy nhấp vào Chỉnh sửa bên cạnh hạn mức mà bạn muốn chỉnh sửa, chẳng hạn như Số yêu cầu chưa ký mỗi ngày.
  6. Trong ngăn Chỉnh sửa hạn mức, hãy cập nhật Hạn mức.
  7. Nhấp vào Lưu.

Ký yêu cầu của bạn

Quy trình ký yêu cầu bao gồm các bước sau:

Bước 1: Lấy khoá bí mật ký URL

Cách lấy khoá bí mật ký URL của dự án:

  1. Chuyển đến trang Thông tin đăng nhập của Google Maps Platform trong Cloud Console.
  2. Chọn trình đơn thả xuống dự án rồi chọn cùng một dự án mà bạn đã dùng khi tạo khoá API cho .
  3. Di chuyển xuống thẻ Secret Generator (Trình tạo khoá bí mật). Trường Khoá bí mật hiện tại chứa khoá bí mật ký URL hiện tại của bạn.
  4. Trang này cũng có tiện ích Ký một URL ngay cho phép bạn tự động ký yêu cầu bằng khoá bí mật ký hiện tại. Di chuyển xuống thẻ Ký URL ngay để truy cập vào thẻ này.

Để nhận một khoá bí mật ký URL mới, hãy chọn Tạo lại khoá bí mật. Khoá bí mật trước đó sẽ hết hạn sau 24 giờ kể từ khi bạn tạo một khoá bí mật mới. Sau 24 giờ, các yêu cầu chứa khoá bí mật cũ sẽ không còn hoạt động nữa.

Bước 2: Tạo yêu cầu chưa ký

Các ký tự không được liệt kê trong bảng dưới đây phải được mã hoá URL:

Tóm tắt các ký tự hợp lệ trong URL
Đặtký tựCách sử dụng URL
Chữ và số a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 Chuỗi văn bản, cách sử dụng lược đồ (http), cổng (8080), v.v.
Không dành riêng - _ . ~ Chuỗi văn bản
Đã đặt trước ! * ' ( ) ; : @ & = + $ , / ? % # [ ] Ký tự điều khiển và/hoặc Chuỗi văn bản

Điều này cũng áp dụng cho mọi ký tự trong tập hợp Reserved (Đã đặt trước), nếu các ký tự đó được truyền bên trong một chuỗi văn bản. Để biết thêm thông tin, hãy xem phần Ký tự đặc biệt.

Tạo URL yêu cầu chưa ký mà không có chữ ký. Để xem hướng dẫn, hãy tham khảo tài liệu sau đây dành cho nhà phát triển:

Hãy nhớ thêm cả khoá API vào tham số key. Ví dụ:

https://maps.googleapis.com/maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEY

Tạo yêu cầu đã ký

Đối với các trường hợp sử dụng một lần, chẳng hạn như lưu trữ một hình ảnh đơn giản của Maps Static API hoặc Street View Static API trên trang web của bạn hoặc cho mục đích khắc phục sự cố, bạn có thể tự động tạo chữ ký số bằng cách sử dụng tiện ích Ký URL ngay hiện có.

Đối với các yêu cầu được tạo động, bạn cần phải ký phía máy chủ. Việc này đòi hỏi thêm một vài bước trung gian

Dù bằng cách nào, bạn cũng sẽ có một URL yêu cầu có tham số signature được nối vào cuối. Ví dụ:

https://maps.googleapis.com/maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEY
&signature=BASE64_SIGNATURE
Sử dụng tiện ích Ký URL ngay

Cách tạo chữ ký số bằng khoá API bằng tiện ích Ký URL ngay trong Google Cloud Console:

  1. Tìm tiện ích Ký URL ngay, như mô tả trong Bước 1: Lấy khoá bí mật ký URL.
  2. Trong trường URL, hãy dán URL yêu cầu chưa ký từ Bước 2: Tạo yêu cầu chưa ký.
  3. Trường URL đã ký của bạn sẽ xuất hiện và chứa URL đã ký bằng chữ ký số của bạn. Nhớ tạo bản sao.
Tạo chữ ký số phía máy chủ

So với tiện ích Ký URL ngay, bạn sẽ cần thực hiện thêm một số thao tác khi tạo chữ ký số phía máy chủ:

  1. Loại bỏ phần tên giao thức và máy chủ của URL, chỉ để lại đường dẫn và truy vấn:

  2. /maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEY
    
  3. Khoá bí mật ký URL được hiển thị được mã hoá theo Base64 đã sửa đổi cho URL.

    Vì hầu hết các thư viện mật mã đều yêu cầu khoá ở định dạng byte thô, nên có thể bạn sẽ cần giải mã khoá bí mật ký URL thành định dạng thô ban đầu trước khi ký.

  4. Ký yêu cầu đã loại bỏ ở trên bằng HMAC-SHA1.
  5. Vì hầu hết các thư viện mật mã đều tạo chữ ký ở định dạng byte thô, nên bạn sẽ cần chuyển đổi chữ ký nhị phân thu được bằng cách sử dụng Base64 đã sửa đổi cho URL để chuyển đổi chữ ký đó thành một thứ có thể được truyền trong URL.

  6. Thêm chữ ký được mã hoá Base64 vào URL yêu cầu ban đầu chưa ký trong tham số signature. Ví dụ:

    https://maps.googleapis.com/maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEY
    &signature=BASE64_SIGNATURE

Để xem các mẫu minh hoạ cách triển khai tính năng ký URL bằng mã phía máy chủ, hãy xem Mã mẫu để ký URL bên dưới.

Mã mẫu để ký URL

Các phần sau đây trình bày những cách triển khai tính năng ký URL bằng mã phía máy chủ. Bạn phải luôn ký URL phía máy chủ để tránh để lộ khoá bí mật ký URL cho người dùng.

Python

Ví dụ bên dưới sử dụng các thư viện Python tiêu chuẩn để ký một URL. (Tải mã xuống.)

#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Signs a URL using a URL signing secret """

import hashlib
import hmac
import base64
import urllib.parse as urlparse


def sign_url(input_url=None, secret=None):
    """ Sign a request URL with a URL signing secret.
      Usage:
      from urlsigner import sign_url
      signed_url = sign_url(input_url=my_url, secret=SECRET)
      Args:
      input_url - The URL to sign
      secret    - Your URL signing secret
      Returns:
      The signed request URL
  """

    if not input_url or not secret:
        raise Exception("Both input_url and secret are required")

    url = urlparse.urlparse(input_url)

    # We only need to sign the path+query part of the string
    url_to_sign = url.path + "?" + url.query

    # Decode the private key into its binary format
    # We need to decode the URL-encoded private key
    decoded_key = base64.urlsafe_b64decode(secret)

    # Create a signature using the private key and the URL-encoded
    # string using HMAC SHA1. This signature will be binary.
    signature = hmac.new(decoded_key, str.encode(url_to_sign), hashlib.sha1)

    # Encode the binary signature into base64 for use within a URL
    encoded_signature = base64.urlsafe_b64encode(signature.digest())

    original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query

    # Return signed URL
    return original_url + "&signature=" + encoded_signature.decode()


if __name__ == "__main__":
    input_url = input("URL to Sign: ")
    secret = input("URL signing secret: ")
    print("Signed URL: " + sign_url(input_url, secret))

Java

Ví dụ dưới đây sử dụng lớp java.util.Base64 có sẵn kể từ JDK 1.8 – các phiên bản cũ hơn có thể cần sử dụng Apache Commons hoặc các phiên bản tương tự. (Tải mã xuống.)

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
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.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class UrlSigner {

  // Note: Generally, you should store your private key someplace safe
  // and read them into your code

  private static String keyString = "YOUR_PRIVATE_KEY";
  
  // The URL shown in these examples is a static URL which should already
  // be URL-encoded. In practice, you will likely have code
  // which assembles your URL from user or web service input
  // and plugs those values into its parameters.
  private static String urlString = "YOUR_URL_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, URISyntaxException {
    
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    
    String inputUrl, inputKey = null;

    // For testing purposes, allow user input for the URL.
    // If no input is entered, use the static URL defined above.    
    System.out.println("Enter the URL (must be URL-encoded) to sign: ");
    inputUrl = input.readLine();
    if (inputUrl.equals("")) {
      inputUrl = urlString;
    }
    
    // Convert the string to a URL so we can parse it
    URL url = new URL(inputUrl);
 
    // For testing purposes, allow user input for the private key.
    // If no input is entered, use the static key defined above.   
    System.out.println("Enter the Private key to sign the URL: ");
    inputKey = input.readLine();
    if (inputKey.equals("")) {
      inputKey = keyString;
    }
    
    UrlSigner signer = new UrlSigner(inputKey);
    String request = signer.signRequest(url.getPath(),url.getQuery());
    
    System.out.println("Signed URL :" + url.getProtocol() + "://" + url.getHost() + request);
  }
  
  public UrlSigner(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 path, String query) throws NoSuchAlgorithmException,
    InvalidKeyException, UnsupportedEncodingException, URISyntaxException {
    
    // Retrieve the proper URL components to sign
    String resource = path + '?' + query;
    
    // 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 resource + "&signature=" + signature;
  }
}

Node JS

Ví dụ bên dưới sử dụng các mô-đun Node gốc để ký một URL. (Tải mã xuống.)

'use strict'

const crypto = require('crypto');
const url = require('url');

/**
 * Convert from 'web safe' base64 to true base64.
 *
 * @param  {string} safeEncodedString The code you want to translate
 *                                    from a web safe form.
 * @return {string}
 */
function removeWebSafe(safeEncodedString) {
  return safeEncodedString.replace(/-/g, '+').replace(/_/g, '/');
}

/**
 * Convert from true base64 to 'web safe' base64
 *
 * @param  {string} encodedString The code you want to translate to a
 *                                web safe form.
 * @return {string}
 */
function makeWebSafe(encodedString) {
  return encodedString.replace(/\+/g, '-').replace(/\//g, '_');
}

/**
 * Takes a base64 code and decodes it.
 *
 * @param  {string} code The encoded data.
 * @return {string}
 */
function decodeBase64Hash(code) {
  // "new Buffer(...)" is deprecated. Use Buffer.from if it exists.
  return Buffer.from ? Buffer.from(code, 'base64') : new Buffer(code, 'base64');
}

/**
 * Takes a key and signs the data with it.
 *
 * @param  {string} key  Your unique secret key.
 * @param  {string} data The url to sign.
 * @return {string}
 */
function encodeBase64Hash(key, data) {
  return crypto.createHmac('sha1', key).update(data).digest('base64');
}

/**
 * Sign a URL using a secret key.
 *
 * @param  {string} path   The url you want to sign.
 * @param  {string} secret Your unique secret key.
 * @return {string}
 */
function sign(path, secret) {
  const uri = url.parse(path);
  const safeSecret = decodeBase64Hash(removeWebSafe(secret));
  const hashedSignature = makeWebSafe(encodeBase64Hash(safeSecret, uri.path));
  return url.format(uri) + '&signature=' + hashedSignature;
}

C#

Ví dụ bên dưới sử dụng thư viện System.Security.Cryptography mặc định để ký một yêu cầu URL. Lưu ý rằng chúng ta cần chuyển đổi chế độ mã hoá Base64 mặc định để triển khai phiên bản an toàn cho URL. (Tải mã xuống.)

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace SignUrl {

  public struct GoogleSignedUrl {

    public static string Sign(string url, string keyString) {
      ASCIIEncoding encoding = new ASCIIEncoding();

      // converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
      string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
      byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);

      Uri uri = new Uri(url);
      byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);

      // compute the hash
      HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
      byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);

      // convert the bytes to string and make url-safe by replacing '+' and '/' characters
      string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");
            
      // Add the signature to the existing URI.
      return uri.Scheme+"://"+uri.Host+uri.LocalPath + uri.Query +"&signature=" + signature;
    }
  }

  class Program {

    static void Main() {
    
      // Note: Generally, you should store your private key someplace safe
      // and read them into your code

      const string keyString = "YOUR_PRIVATE_KEY";
  
      // The URL shown in these examples is a static URL which should already
      // be URL-encoded. In practice, you will likely have code
      // which assembles your URL from user or web service input
      // and plugs those values into its parameters.
      const  string urlString = "YOUR_URL_TO_SIGN";
      
      string inputUrl = null;
      string inputKey = null;
    
      Console.WriteLine("Enter the URL (must be URL-encoded) to sign: ");
      inputUrl = Console.ReadLine();
      if (inputUrl.Length == 0) {
        inputUrl = urlString;
      }     
    
      Console.WriteLine("Enter the Private key to sign the URL: ");
      inputKey = Console.ReadLine();
      if (inputKey.Length == 0) {
        inputKey = keyString;
      }
      
      Console.WriteLine(GoogleSignedUrl.Sign(inputUrl,inputKey));
    }
  }
}

Ví dụ bằng các ngôn ngữ khác

Bạn có thể xem các ví dụ hỗ trợ nhiều ngôn ngữ hơn trong dự án url-signing.

Khắc phục sự cố

Nếu yêu cầu có chữ ký không hợp lệ, API sẽ trả về lỗi HTTP 403 (Forbidden). Lỗi này thường xảy ra nếu bí mật ký được sử dụng không liên kết với khoá API đã truyền hoặc nếu đầu vào không phải ASCII không được mã hoá URL trước khi ký.

Để khắc phục vấn đề này, hãy sao chép URL yêu cầu, xoá tham số truy vấn signature và tạo lại chữ ký hợp lệ theo hướng dẫn bên dưới:

Cách tạo chữ ký số bằng khoá API bằng tiện ích Ký URL ngay trong Google Cloud Console:

  1. Tìm tiện ích Ký URL ngay, như mô tả trong Bước 1: Lấy khoá bí mật ký URL.
  2. Trong trường URL, hãy dán URL yêu cầu chưa ký từ Bước 2: Tạo yêu cầu chưa ký.
  3. Trường URL đã ký của bạn sẽ xuất hiện và chứa URL đã ký bằng chữ ký số của bạn. Nhớ tạo bản sao.