मुझे डेटा एन्क्रिप्ट (सुरक्षित) करना है

हम डेटा एन्क्रिप्शन के ज़्यादातर इस्तेमाल के लिए, AES128_GCM कुंजी टाइप के साथ, AEAD प्रिमिटिव को इस्तेमाल करने का सुझाव देते हैं.

असोसिएट किए गए डेटा के साथ पुष्टि किया हुआ एन्क्रिप्शन (AEAD), इस्तेमाल के ज़्यादातर मामलों के लिए सबसे आसान और सबसे सही शुरुआती तरीका है. AEAD, सुरक्षा और प्रामाणिकता देता है. साथ ही, यह पक्का करता है कि मैसेज में हमेशा अलग-अलग सादे टेक्स्ट (एन्क्रिप्ट किए गए आउटपुट) हों, भले ही सादे टेक्स्ट (एन्क्रिप्ट करने के लिए इनपुट) एक जैसे हों. यह सिमेट्रिक है, जिसमें एन्क्रिप्शन और डिक्रिप्शन, दोनों के लिए एक ही कुंजी का इस्तेमाल किया जाता है.

नीचे दिए गए उदाहरणों से आप AEAD प्रिमिटिव का इस्तेमाल शुरू कर सकते हैं:

C++

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

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/log/check.h"
#include "absl/strings/string_view.h"
#include "tink/aead.h"
#include "tink/aead/aead_config.h"
#include "util/util.h"
#include "tink/keyset_handle.h"
#include "tink/util/status.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::AeadConfig;
using ::crypto::tink::KeysetHandle;
using ::crypto::tink::util::Status;
using ::crypto::tink::util::StatusOr;

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

void ValidateParams() {
  // ...
}

}  // namespace

namespace tink_cc_examples {

// AEAD example CLI implementation.
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) {
  Status result = AeadConfig::Register();
  if (!result.ok()) return result;

  // Read the keyset from file.
  StatusOr<std::unique_ptr<KeysetHandle>> keyset_handle =
      ReadJsonCleartextKeyset(keyset_filename);
  if (!keyset_handle.ok()) return keyset_handle.status();

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

  // Read the input.
  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) {
    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.
    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 << "'." << std::endl;
  std::clog << "The resulting output will be written to " << output_filename
            << std::endl;

  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
}

Java

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.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(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 का इस्तेमाल करें.

आपके बच्चे का डेटा

AEAD का इस्तेमाल किसी खास असोसिएट डेटा से साइफ़रटेक्स्ट को जोड़ने के लिए किया जा सकता है. मान लें कि आपके पास user-id और encrypted-medical-history फ़ील्ड वाला एक डेटाबेस है. इस स्थिति में, encrypted-medical-history को एन्क्रिप्ट करते समय user-id का इस्तेमाल, इससे जुड़े डेटा के तौर पर किया जा सकता है. यह किसी हमलावर को एक उपयोगकर्ता से दूसरे उपयोगकर्ता के मेडिकल इतिहास को ट्रांसफ़र करने से रोकता है.

कोई कुंजी टाइप चुनें

हमारा सुझाव है कि ज़्यादातर मामलों में AES128_GCM का इस्तेमाल करें. हालांकि, अलग-अलग ज़रूरतों के लिए अलग-अलग तरह की कुंजी हैं. 256-बिट सुरक्षा के लिए, AES128 को नीचे दिए गए AES256 से बदलें. आम तौर पर ये उपाय अपनाएं:

  • अच्छी सीमाओं वाला 16-बाइट इनिशलाइज़ेशन वेक्टर (IV) वाला AES128_CTR_HMAC_SHA256 सबसे पुराना मोड है.
  • AES128_EAX थोड़ा कम कंज़र्वेटिव है और AES128_CTR_HMAC_SHA256 से थोड़ा तेज़ है.
  • आम तौर पर, AES128_GCM सबसे तेज़ मोड होता है. इसमें मैसेज की संख्या और मैसेज के साइज़ की सीमा सबसे ज़्यादा होती है. जब सादे टेक्स्ट और उससे जुड़े डेटा की लंबाई (नीचे) पार हो जाती है, तो AES128_GCM काम नहीं करता और अहम सामग्री लीक हो जाती है.
  • AES128_GCM_SIV करीब-करीब AES128_GCM जितना तेज़ है, लेकिन इसमें बहुत सारे मैसेज शामिल हैं. हालांकि, इसकी पहुंच थोड़ी कम है. इसे Java में इस्तेमाल करने के लिए, आपको Conscrypt इंस्टॉल करना होगा.
  • AES128_GCM के मुकाबले, XChaCha20Poly1305 में मैसेज की संख्या और मैसेज के साइज़ की सीमा बहुत ज़्यादा है. हालांकि, ऐसा न होने पर (बहुत कम) ऐसा करने से अहम कॉन्टेंट भी लीक हो जाता है. यह हार्डवेयर एक्सेलरेटेड नहीं है. इसलिए, यह उन स्थितियों में एईएस मोड से धीमा हो सकता है जहां हार्डवेयर से तेज़ी लाने की सुविधा उपलब्ध हो.

सुरक्षा की गारंटी

AEAD में लागू करने की सुविधा:

  • CCA2 सुरक्षा.
  • पुष्टि करने की कम से कम 80-बिट.
  • कुल 250 बाइट वाले कम से कम 232 मैसेज को एन्क्रिप्ट (सुरक्षित) करने की सुविधा. ज़्यादा से ज़्यादा 232 सादे टेक्स्ट चुने गए या चुने गए सादे टेक्स्ट के साथ किसी भी अटैक के सफल होने की संभावना 2-32 से ज़्यादा नहीं होने की संभावना है.