أريد تشفير البيانات

ننصح باستخدام بدائية AEAD مع نوع مفتاح AES128_GCM لمعظم حالات استخدام تشفير البيانات.

التشفير المصادَق عليه باستخدام البيانات المرتبطة (AEAD) هو البدائية الأبسط والأكثر ملاءمة لمعظم حالات الاستخدام. توفّر بدائية AEAD السرية والمصداقية وتضمن أن يكون للنصوص المشفرة (المخرجات المشفّرة) دائمًا قيم مختلفة حتى إذا كانت النصوص العادية (مدخلات التشفير) متطابقة. وهي بدائية متماثلة، أي تستخدم مفتاحًا واحدًا لكل من التشفير وفك التشفير.

في ما يلي بعض الأمثلة التي تساعدك على البدء في استخدام بدائية AEAD:

C++‎

// A command-line utility for testing Tink AEAD.
#include <iostream>
#include <memory>
#include <string>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "tink/aead.h"
#include "tink/aead/config_v0.h"
#include "util/util.h"
#include "tink/keyset_handle.h"

ABSL_FLAG(std::string, keyset_filename, "", "Keyset file in JSON format");
ABSL_FLAG(std::string, mode, "", "Mode of operation {encrypt|decrypt}");
ABSL_FLAG(std::string, input_filename, "", "Filename to operate on");
ABSL_FLAG(std::string, output_filename, "", "Output file name");
ABSL_FLAG(std::string, associated_data, "",
          "Associated data for AEAD (default: empty");

namespace {

using ::crypto::tink::Aead;
using ::crypto::tink::KeysetHandle;

constexpr absl::string_view kEncrypt = "encrypt";
constexpr absl::string_view kDecrypt = "decrypt";

void ValidateParams() {
  // ...
}

}  // namespace

namespace tink_cc_examples {

// AEAD example CLI implementation.
absl::Status AeadCli(absl::string_view mode, const std::string& keyset_filename,
                     const std::string& input_filename,
                     const std::string& output_filename,
                     absl::string_view associated_data) {
  // Read the keyset from file.
  absl::StatusOr<std::unique_ptr<KeysetHandle>> keyset_handle =
      ReadJsonCleartextKeyset(keyset_filename);
  if (!keyset_handle.ok()) return keyset_handle.status();

  // Get the primitive.
  absl::StatusOr<std::unique_ptr<Aead>> aead =
      (*keyset_handle)
          ->GetPrimitive<crypto::tink::Aead>(crypto::tink::ConfigAeadV0());
  if (!aead.ok()) return aead.status();

  // Read the input.
  absl::StatusOr<std::string> input_file_content = ReadFile(input_filename);
  if (!input_file_content.ok()) return input_file_content.status();

  // Compute the output.
  std::string output;
  if (mode == kEncrypt) {
    absl::StatusOr<std::string> encrypt_result =
        (*aead)->Encrypt(*input_file_content, associated_data);
    if (!encrypt_result.ok()) return encrypt_result.status();
    output = encrypt_result.value();
  } else {  // operation == kDecrypt.
    absl::StatusOr<std::string> decrypt_result =
        (*aead)->Decrypt(*input_file_content, associated_data);
    if (!decrypt_result.ok()) return decrypt_result.status();
    output = decrypt_result.value();
  }

  // Write the output to the output file.
  return WriteToFile(output, output_filename);
}

}  // namespace tink_cc_examples

int main(int argc, char** argv) {
  absl::ParseCommandLine(argc, argv);

  ValidateParams();

  std::string mode = absl::GetFlag(FLAGS_mode);
  std::string keyset_filename = absl::GetFlag(FLAGS_keyset_filename);
  std::string input_filename = absl::GetFlag(FLAGS_input_filename);
  std::string output_filename = absl::GetFlag(FLAGS_output_filename);
  std::string associated_data = absl::GetFlag(FLAGS_associated_data);

  std::clog << "Using keyset from file " << keyset_filename << " to AEAD-"
            << mode << " file " << input_filename << " with associated data '"
            << associated_data << "'." << '\n';
  std::clog << "The resulting output will be written to " << output_filename
            << '\n';

  ABSL_CHECK_OK(tink_cc_examples::AeadCli(mode, keyset_filename, input_filename,
                                          output_filename, associated_data));
  return 0;
}

انتقال

import (
	"bytes"
	"fmt"
	"log"

	"github.com/tink-crypto/tink-go/v2/aead"
	"github.com/tink-crypto/tink-go/v2/insecurecleartextkeyset"
	"github.com/tink-crypto/tink-go/v2/keyset"
)

func Example() {
	// A keyset created with "tinkey create-keyset --key-template=AES256_GCM". Note
	// that this keyset has the secret key information in cleartext.
	jsonKeyset := `{
			"key": [{
					"keyData": {
							"keyMaterialType":
									"SYMMETRIC",
							"typeUrl":
									"type.googleapis.com/google.crypto.tink.AesGcmKey",
							"value":
									"GiBWyUfGgYk3RTRhj/LIUzSudIWlyjCftCOypTr0jCNSLg=="
					},
					"keyId": 294406504,
					"outputPrefixType": "TINK",
					"status": "ENABLED"
			}],
			"primaryKeyId": 294406504
	}`

	// Create a keyset handle from the cleartext keyset in the previous
	// step. The keyset handle provides abstract access to the underlying keyset to
	// limit the exposure of accessing the raw key material. WARNING: In practice,
	// it is unlikely you will want to use a insecurecleartextkeyset, as it implies
	// that your key material is passed in cleartext, which is a security risk.
	// Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault.
	// See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets.
	keysetHandle, err := insecurecleartextkeyset.Read(
		keyset.NewJSONReader(bytes.NewBufferString(jsonKeyset)))
	if err != nil {
		log.Fatal(err)
	}

	// Retrieve the AEAD primitive we want to use from the keyset handle.
	primitive, err := aead.New(keysetHandle)
	if err != nil {
		log.Fatal(err)
	}

	// Use the primitive to encrypt a message. In this case the primary key of the
	// keyset will be used (which is also the only key in this example).
	plaintext := []byte("message")
	associatedData := []byte("associated data")
	ciphertext, err := primitive.Encrypt(plaintext, associatedData)
	if err != nil {
		log.Fatal(err)
	}

	// Use the primitive to decrypt the message. Decrypt finds the correct key in
	// the keyset and decrypts the ciphertext. If no key is found or decryption
	// fails, it returns an error.
	decrypted, err := primitive.Decrypt(ciphertext, associatedData)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(decrypted))
	// Output: message
}

جافا

package aead;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.crypto.tink.Aead;
import com.google.crypto.tink.InsecureSecretKeyAccess;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.RegistryConfiguration;
import com.google.crypto.tink.TinkJsonProtoKeysetFormat;
import com.google.crypto.tink.aead.AeadConfig;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * A command-line utility for encrypting small files with AEAD.
 *
 * <p>It loads cleartext keys from disk - this is not recommended!
 *
 * <p>It requires the following arguments:
 *
 * <ul>
 *   <li>mode: Can be "encrypt" or "decrypt" to encrypt/decrypt the input to the output.
 *   <li>key-file: Read the key material from this file.
 *   <li>input-file: Read the input from this file.
 *   <li>output-file: Write the result to this file.
 *   <li>[optional] associated-data: Associated data used for the encryption or decryption.
 */
public final class AeadExample {
  private static final String MODE_ENCRYPT = "encrypt";
  private static final String MODE_DECRYPT = "decrypt";

  public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
      System.err.printf("Expected 4 or 5 parameters, got %d\n", args.length);
      System.err.println(
          "Usage: java AeadExample encrypt/decrypt key-file input-file output-file"
              + " [associated-data]");
      System.exit(1);
    }
    String mode = args[0];
    Path keyFile = Paths.get(args[1]);
    Path inputFile = Paths.get(args[2]);
    Path outputFile = Paths.get(args[3]);
    byte[] associatedData = new byte[0];
    if (args.length == 5) {
      associatedData = args[4].getBytes(UTF_8);
    }
    // Register all AEAD key types with the Tink runtime.
    AeadConfig.register();

    // Read the keyset into a KeysetHandle.
    KeysetHandle handle =
        TinkJsonProtoKeysetFormat.parseKeyset(
            new String(Files.readAllBytes(keyFile), UTF_8), InsecureSecretKeyAccess.get());

    // Get the primitive.
    Aead aead = handle.getPrimitive(RegistryConfiguration.get(), Aead.class);

    // Use the primitive to encrypt/decrypt files.
    if (MODE_ENCRYPT.equals(mode)) {
      byte[] plaintext = Files.readAllBytes(inputFile);
      byte[] ciphertext = aead.encrypt(plaintext, associatedData);
      Files.write(outputFile, ciphertext);
    } else if (MODE_DECRYPT.equals(mode)) {
      byte[] ciphertext = Files.readAllBytes(inputFile);
      byte[] plaintext = aead.decrypt(ciphertext, associatedData);
      Files.write(outputFile, plaintext);
    } else {
      System.err.println("The first argument must be either encrypt or decrypt, got: " + mode);
      System.exit(1);
    }
  }

  private AeadExample() {}
}

Obj-C

كيفية التنفيذ

Python

import tink
from tink import aead
from tink import secret_key_access


def example():
  """Encrypt and decrypt using AEAD."""
  # Register the AEAD key managers. This is needed to create an Aead primitive
  # later.
  aead.register()

  # A keyset created with "tinkey create-keyset --key-template=AES256_GCM". Note
  # that this keyset has the secret key information in cleartext.
  keyset = r"""{
      "key": [{
          "keyData": {
              "keyMaterialType":
                  "SYMMETRIC",
              "typeUrl":
                  "type.googleapis.com/google.crypto.tink.AesGcmKey",
              "value":
                  "GiBWyUfGgYk3RTRhj/LIUzSudIWlyjCftCOypTr0jCNSLg=="
          },
          "keyId": 294406504,
          "outputPrefixType": "TINK",
          "status": "ENABLED"
      }],
      "primaryKeyId": 294406504
  }"""

  # Create a keyset handle from the cleartext keyset in the previous
  # step. The keyset handle provides abstract access to the underlying keyset to
  # limit access of the raw key material. WARNING: In practice, it is unlikely
  # you will want to use a cleartext_keyset_handle, as it implies that your key
  # material is passed in cleartext, which is a security risk.
  keyset_handle = tink.json_proto_keyset_format.parse(
      keyset, secret_key_access.TOKEN
  )

  # Retrieve the Aead primitive we want to use from the keyset handle.
  primitive = keyset_handle.primitive(aead.Aead)

  # Use the primitive to encrypt a message. In this case the primary key of the
  # keyset will be used (which is also the only key in this example).
  ciphertext = primitive.encrypt(b'msg', b'associated_data')

  # Use the primitive to decrypt the message. Decrypt finds the correct key in
  # the keyset and decrypts the ciphertext. If no key is found or decryption
  # fails, it raises an error.
  output = primitive.decrypt(ciphertext, b'associated_data')

AEAD

بدائية التشفير المصادَق عليه باستخدام البيانات المرتبطة (AEAD) هي البدائية الأكثر شيوعًا لتشفير البيانات وتناسب معظم الاحتياجات.

تتضمّن بدائية AEAD الخصائص التالية:

  • Secrecy: لا يُعرف أي شيء عن النص العادي، باستثناء طوله.
  • المصداقية: من المستحيل تغيير النص العادي المشفّر الأساسي للنص المشفر بدون أن يتم اكتشاف ذلك.
  • التماثل: يتم تشفير النص العادي وفك تشفير النص المشفر باستخدام المفتاح نفسه.
  • التوزيع العشوائي: يتم التشفير بشكل عشوائي. تؤدي رسالتان تتضمّنان النص العادي نفسه إلى نصوص مشفرة مختلفة. لا يمكن للمهاجمين معرفة النص المشفر الذي يتطابق مع نص عادي معيّن. إذا أردت تجنُّب ذلك، استخدِم بدائية AEAD الحتمية بدلاً من ذلك.

البيانات المرتبطة

يمكن استخدام بدائية AEAD لـ ربط النص المشفر ببيانات مرتبطة معيّنة بيانات. لنفترض أنّ لديك قاعدة بيانات تتضمّن الحقلَين user-id وencrypted-medical-history. في هذا السيناريو، يمكن استخدام user-id كبيانات مرتبطة عند تشفير encrypted-medical-history. يمنع ذلك المهاجم من نقل السجلّ الطبي من مستخدم إلى آخر.

البيانات المرتبطة اختيارية. في حال تحديدها، لا تنجح عملية فك التشفير إلا إذا تم تمرير البيانات المرتبطة نفسها إلى كل من طلبَي التشفير وفك التشفير.

اختيار نوع المفتاح

ننصح باستخدام AES128_GCM لمعظم حالات الاستخدام، ولكن هناك أنواع مفاتيح مختلفة لتلبية الاحتياجات المختلفة. يوفّر AES128 أمانًا بمستوى 128 بت، بينما يوفّر AES256 أمانًا بمستوى 256 بت.

في ما يلي قيود الأمان البارزة عند اختيار وضع معيّن:

  1. عدد الطلبات في الثانية (QPS): كم عدد الرسائل التي يتم تشفيرها باستخدام المفتاح نفسه؟
  2. حجم الرسالة: ما هو حجم الرسائل؟

أنواع المفاتيح المتوافقة:

  • تشفير AES-CTR-HMAC (AES128_CTR_HMAC_SHA256 وAES256_CTR_HMAC_SHA256) مع متّجه تهيئة (IV) بطول 16 بايت هو الوضع الأكثر تحفّظًا مع حدود جيدة.
    • الالتزام بالمفتاح
  • تشفير AES-EAX (AES128_EAX وAES256_EAX) أقل تحفّظًا وأسرع قليلاً من AES128_CTR_HMAC_SHA256.
    • لا يلتزم MLGR بالمفتاح.
  • تشفير AES-GCM (AES128_GCM وAES256_GCM) هو عادةً الوضع الأسرع مع القيود الأكثر صرامة على عدد الرسائل وحجم الرسالة. عند تجاوز هذه الحدود على أطوال النص العادي والبيانات المرتبطة (الموضّحة أدناه)، يفشل تشفير AES-GCM بشكل كارثي من خلال تسريب النص العادي وجزء المصادقة من المفتاح الداخلي لتشفير AES-GCM.
    • تشفير AES-GCM ليس قويًا [ABN] ولا يلتزم بالمفتاح [GLR]. من الممكن إنشاء نص مشفر يمكن فك تشفيره باستخدام مفتاحَين مختلفَين. يمكن أن يؤدي ذلك إلى هجمات عملية [DGRW]. راجِع نموذج التهديد بعناية إذا اختار الخصم المفتاح.
  • تشفير AES-GCM-SIV (AES128_GCM_SIV وAES256_GCM_SIV) سريع تقريبًا مثل تشفير AES-GCM. وله الحدود نفسها التي يفرضها تشفير AES-GCM على عدد الرسائل وحجم الرسالة، ولكن عند تجاوز هذه الحدود، يفشل بطريقة أقل كارثية: قد يؤدي ذلك إلى تسريب حقيقة أنّ رسالتَين متساويتان فقط. يُعدّ هذا التشفير أكثر أمانًا من تشفير AES-GCM، ولكنّه أقل استخدامًا على نطاق واسع في الممارسة العملية. لاستخدام هذا في Java، عليك تثبيت Conscrypt.
    • لا يلتزم ADGKLS بالمفتاح.
  • تشفير XChaCha20-Poly1305 (XCHACHA20_POLY1305) يفرض حدًا أكبر بكثير على عدد الرسائل وحجم الرسالة مقارنةً بتشفير AES-GCM، ولكن عند فشله (وهو أمر غير مرجّح)، يؤدي أيضًا إلى تسريب مواد المفتاح. لا يتم تسريع هذا التشفير على مستوى الأجهزة، لذا قد يكون أبطأ من أوضاع تشفير AES في الحالات التي يتوفّر فيها تسريع الأجهزة.
    • لا يلتزم LGR بالمفتاح.

مزيد من المعلومات حول تنسيق النقل للنص المشفر بتشفير AEAD

الضمانات الأمنية

توفّر عمليات تنفيذ تشفير AEAD ما يلي:

  • أمان CCA2
  • قوة مصادقة لا تقل عن 80 بت
  • إمكانية تشفير ما لا يقل عن 232 رسالة بإجمالي 250 بايت لا يوجد هجوم باستخدام ما يصل إلى 232 نصًا عاديًا أو نصًا مشفرًا تم اختيارهما، تكون احتمالية نجاحه أكبر من 2-32.