یک مجموعه کلید در متن ساده ایجاد و ذخیره کنید
با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
مثالهای زیر نحوه ایجاد یک مجموعه کلید با یک کلید و ذخیره آن را در متن ساده روی دیسک نشان میدهند.
تینکی
tinkey create-keyset \
--key-template AES128_GCM \
--out-format json \
--out aead_keyset.json
جاوا
package cleartextkeyset;
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 com.google.crypto.tink.aead.PredefinedAeadParameters;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* A command-line utility for generating, storing and using AES128_GCM keysets.
*
* <h1>WARNING: Loading a Keyset from disk is often a security problem -- hence this needs {@code
* InsecureSecretKeyAccess.get()}.
*
* <p>It requires the following arguments:
*
* <ul>
* <li>mode: Can be "generate", "encrypt" or "decrypt". If mode is "generate" it will generate,
* encrypt a keyset, store it in key-file. If mode is "encrypt" or "decrypt" it will read and
* decrypt an keyset from key-file, and use it to encrypt or decrypt input-file.
* <li>key-file: Read the encrypted key material from this file.
* <li>input-file: If mode is "encrypt" or "decrypt", read the input from this file.
* <li>output-file: If mode is "encrypt" or "decrypt", write the result to this file.
*/
public final class CleartextKeysetExample {
private static final String MODE_ENCRYPT = "encrypt";
private static final String MODE_DECRYPT = "decrypt";
private static final String MODE_GENERATE = "generate";
private static final byte[] EMPTY_ASSOCIATED_DATA = new byte[0];
public static void main(String[] args) throws Exception {
if (args.length != 2 && args.length != 4) {
System.err.printf("Expected 2 or 4 parameters, got %d\n", args.length);
System.err.println(
"Usage: java CleartextKeysetExample generate/encrypt/decrypt key-file input-file"
+ " output-file");
System.exit(1);
}
String mode = args[0];
if (!MODE_ENCRYPT.equals(mode) && !MODE_DECRYPT.equals(mode) && !MODE_GENERATE.equals(mode)) {
System.err.print("The first argument should be either encrypt, decrypt or generate");
System.exit(1);
}
Path keyFile = Paths.get(args[1]);
// Initialise Tink: register all AEAD key types with the Tink runtime
AeadConfig.register();
if (MODE_GENERATE.equals(mode)) {
KeysetHandle handle = KeysetHandle.generateNew(PredefinedAeadParameters.AES128_GCM);
String serializedKeyset =
TinkJsonProtoKeysetFormat.serializeKeyset(handle, InsecureSecretKeyAccess.get());
Files.write(keyFile, serializedKeyset.getBytes(UTF_8));
return;
}
// Use the primitive to encrypt/decrypt files
// Read the keyset from disk
String serializedKeyset = new String(Files.readAllBytes(keyFile), UTF_8);
KeysetHandle handle =
TinkJsonProtoKeysetFormat.parseKeyset(serializedKeyset, InsecureSecretKeyAccess.get());
// Get the primitive
Aead aead = handle.getPrimitive(RegistryConfiguration.get(), Aead.class);
byte[] input = Files.readAllBytes(Paths.get(args[2]));
Path outputFile = Paths.get(args[3]);
if (MODE_ENCRYPT.equals(mode)) {
byte[] ciphertext = aead.encrypt(input, EMPTY_ASSOCIATED_DATA);
Files.write(outputFile, ciphertext);
} else if (MODE_DECRYPT.equals(mode)) {
byte[] plaintext = aead.decrypt(input, EMPTY_ASSOCIATED_DATA);
Files.write(outputFile, plaintext);
}
}
private CleartextKeysetExample() {}
}
برو
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_cleartextKeysetInBinary() {
// Generate a new keyset handle for the primitive we want to use.
handle, err := keyset.NewHandle(aead.AES256GCMKeyTemplate())
if err != nil {
log.Fatal(err)
}
// Serialize the keyset.
buff := &bytes.Buffer{}
err = insecurecleartextkeyset.Write(handle, keyset.NewBinaryWriter(buff))
if err != nil {
log.Fatal(err)
}
serializedKeyset := buff.Bytes()
// serializedKeyset can now be stored at a secure location.
// WARNING: Storing the keyset in cleartext to disk is not recommended!
// Parse the keyset.
parsedHandle, err := insecurecleartextkeyset.Read(
keyset.NewBinaryReader(bytes.NewBuffer(serializedKeyset)))
if err != nil {
log.Fatal(err)
}
// Get the primitive.
primitive, err := aead.New(parsedHandle)
if err != nil {
log.Fatal(err)
}
// Use the primitive.
plaintext := []byte("message")
associatedData := []byte("example encryption")
ciphertext, err := primitive.Encrypt(plaintext, associatedData)
if err != nil {
log.Fatal(err)
}
decrypted, err := primitive.Decrypt(ciphertext, associatedData)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(decrypted))
// Output: message
}
پایتون
"""A command-line utility for generating, storing and using cleartext AES128_GCM keysets.
It loads cleartext keys from disk - this is not recommended!
"""
from absl import app
from absl import flags
from absl import logging
import tink
from tink import aead
from tink import secret_key_access
FLAGS = flags.FLAGS
flags.DEFINE_enum('mode', None, ['generate', 'encrypt', 'decrypt'],
'The operation to perform.')
flags.DEFINE_string('keyset_path', None,
'Path to the keyset used for encryption.')
flags.DEFINE_string('input_path', None, 'Path to the input file.')
flags.DEFINE_string('output_path', None, 'Path to the output file.')
def main(argv):
del argv # Unused.
# Initialise Tink
aead.register()
if FLAGS.mode == 'generate':
# Generate a new keyset
try:
key_template = aead.aead_key_templates.AES128_GCM
keyset_handle = tink.new_keyset_handle(key_template)
except tink.TinkError as e:
logging.exception('Error creating primitive: %s', e)
return 1
with open(FLAGS.keyset_path, 'wt') as keyset_file:
try:
serialized_keyset = tink.json_proto_keyset_format.serialize(
keyset_handle, secret_key_access.TOKEN
)
keyset_file.write(serialized_keyset)
except tink.TinkError as e:
logging.exception('Error writing key: %s', e)
return 1
return 0
# Use the input keyset to encrypt/decrypt data
# Read the keyset into a keyset_handle
with open(FLAGS.keyset_path, 'rt') as keyset_file:
try:
serialized_keyset = keyset_file.read()
keyset_handle = tink.json_proto_keyset_format.parse(
serialized_keyset, secret_key_access.TOKEN
)
except tink.TinkError as e:
logging.exception('Error reading key: %s', e)
return 1
# Get the primitive
try:
cipher = keyset_handle.primitive(aead.Aead)
except tink.TinkError as e:
logging.error('Error creating primitive: %s', e)
return 1
with open(FLAGS.input_path, 'rb') as input_file:
input_data = input_file.read()
if FLAGS.mode == 'decrypt':
output_data = cipher.decrypt(input_data, b'envelope_example')
elif FLAGS.mode == 'encrypt':
output_data = cipher.encrypt(input_data, b'envelope_example')
else:
logging.error(
'Error mode not supported. Please choose "encrypt" or "decrypt".')
return 1
with open(FLAGS.output_path, 'wb') as output_file:
output_file.write(output_data)
if __name__ == '__main__':
flags.mark_flags_as_required(['mode', 'keyset_path'])
app.run(main)
جز در مواردی که غیر از این ذکر شده باشد،محتوای این صفحه تحت مجوز Creative Commons Attribution 4.0 License است. نمونه کدها نیز دارای مجوز Apache 2.0 License است. برای اطلاع از جزئیات، به خطمشیهای سایت Google Developers مراجعه کنید. جاوا علامت تجاری ثبتشده Oracle و/یا شرکتهای وابسته به آن است.
تاریخ آخرین بهروزرسانی 2025-07-25 بهوقت ساعت هماهنگ جهانی.
[null,null,["تاریخ آخرین بهروزرسانی 2025-07-25 بهوقت ساعت هماهنگ جهانی."],[[["\u003cp\u003eThis page demonstrates how to create and use cleartext keysets for encryption and decryption with Tink, but strongly advises against storing keysets in plaintext due to security risks.\u003c/p\u003e\n"],["\u003cp\u003eInstead of storing keysets in plaintext, it recommends encrypting them for secure storage, providing a link to instructions on how to generate encrypted keysets.\u003c/p\u003e\n"],["\u003cp\u003eExamples of cleartext keyset creation and usage are given in Tinkey, Java, Go, and Python for illustrative purposes despite the security concerns.\u003c/p\u003e\n"]]],["The content demonstrates creating and storing keysets in plaintext, which is discouraged due to security risks. It details using `tinkey` to create an AES128_GCM keyset and save it as a JSON file. Java, Go, and Python examples show how to generate a keyset, serialize it, store it (not recommended), read it back, and use it for encryption and decryption with a specified file for input and output. All codes register the config, generate a key, then encrypt or decrypt depending on the mode.\n"],null,["# Create and store a keyset in plaintext\n\n| **Caution:** We don't recommend storing keysets in plaintext, as keys are often leaked when stored in plaintext. Instead, we recommend [storing encrypted keysets](/tink/generate-encrypted-keyset).\n\nThe following examples show how to create a keyset with a single key and\nstore it in plaintext on disk. \n\n### Tinkey\n\n tinkey create-keyset \\\n --key-template AES128_GCM \\\n --out-format json \\\n --out aead_keyset.json\n\n### Java\n\n\n```java\npackage cleartextkeyset;\n\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\nimport com.google.crypto.tink.Aead;\nimport com.google.crypto.tink.InsecureSecretKeyAccess;\nimport com.google.crypto.tink.KeysetHandle;\nimport com.google.crypto.tink.RegistryConfiguration;\nimport com.google.crypto.tink.TinkJsonProtoKeysetFormat;\nimport com.google.crypto.tink.aead.AeadConfig;\nimport com.google.crypto.tink.aead.PredefinedAeadParameters;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\n/**\n * A command-line utility for generating, storing and using AES128_GCM keysets.\n *\n * \u003ch1\u003eWARNING: Loading a Keyset from disk is often a security problem -- hence this needs {@code\n * InsecureSecretKeyAccess.get()}.\n *\n * \u003cp\u003eIt requires the following arguments:\n *\n * \u003cul\u003e\n * \u003cli\u003emode: Can be \"generate\", \"encrypt\" or \"decrypt\". If mode is \"generate\" it will generate,\n * encrypt a keyset, store it in key-file. If mode is \"encrypt\" or \"decrypt\" it will read and\n * decrypt an keyset from key-file, and use it to encrypt or decrypt input-file.\n * \u003cli\u003ekey-file: Read the encrypted key material from this file.\n * \u003cli\u003einput-file: If mode is \"encrypt\" or \"decrypt\", read the input from this file.\n * \u003cli\u003eoutput-file: If mode is \"encrypt\" or \"decrypt\", write the result to this file.\n */\npublic final class CleartextKeysetExample {\n private static final String MODE_ENCRYPT = \"encrypt\";\n private static final String MODE_DECRYPT = \"decrypt\";\n private static final String MODE_GENERATE = \"generate\";\n private static final byte[] EMPTY_ASSOCIATED_DATA = new byte[0];\n\n public static void main(String[] args) throws Exception {\n if (args.length != 2 && args.length != 4) {\n System.err.printf(\"Expected 2 or 4 parameters, got %d\\n\", args.length);\n System.err.println(\n \"Usage: java CleartextKeysetExample generate/encrypt/decrypt key-file input-file\"\n + \" output-file\");\n System.exit(1);\n }\n String mode = args[0];\n if (!MODE_ENCRYPT.equals(mode) && !MODE_DECRYPT.equals(mode) && !MODE_GENERATE.equals(mode)) {\n System.err.print(\"The first argument should be either encrypt, decrypt or generate\");\n System.exit(1);\n }\n Path keyFile = Paths.get(args[1]);\n\n // Initialise Tink: register all AEAD key types with the Tink runtime\n AeadConfig.register();\n\n if (MODE_GENERATE.equals(mode)) {\n KeysetHandle handle = KeysetHandle.generateNew(PredefinedAeadParameters.AES128_GCM);\n\n String serializedKeyset =\n TinkJsonProtoKeysetFormat.serializeKeyset(handle, InsecureSecretKeyAccess.get());\n Files.write(keyFile, serializedKeyset.getBytes(UTF_8));\n return;\n }\n\n // Use the primitive to encrypt/decrypt files\n\n // Read the keyset from disk\n String serializedKeyset = new String(Files.readAllBytes(keyFile), UTF_8);\n KeysetHandle handle =\n TinkJsonProtoKeysetFormat.parseKeyset(serializedKeyset, InsecureSecretKeyAccess.get());\n\n // Get the primitive\n Aead aead = handle.getPrimitive(RegistryConfiguration.get(), Aead.class);\n\n byte[] input = Files.readAllBytes(Paths.get(args[2]));\n Path outputFile = Paths.get(args[3]);\n\n if (MODE_ENCRYPT.equals(mode)) {\n byte[] ciphertext = aead.encrypt(input, EMPTY_ASSOCIATED_DATA);\n Files.write(outputFile, ciphertext);\n } else if (MODE_DECRYPT.equals(mode)) {\n byte[] plaintext = aead.decrypt(input, EMPTY_ASSOCIATED_DATA);\n Files.write(outputFile, plaintext);\n }\n }\n\n private CleartextKeysetExample() {}\n}https://github.com/tink-crypto/tink-java/blob/50ca1dd9db5cc338d4c1d96a6c978a1da7b61c7b/examples/cleartextkeyset/CleartextKeysetExample.java#L15-L106\n```\n\n\u003cbr /\u003e\n\n### Go\n\n\n```go\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/tink-crypto/tink-go/v2/aead\"\n\t\"github.com/tink-crypto/tink-go/v2/insecurecleartextkeyset\"\n\t\"github.com/tink-crypto/tink-go/v2/keyset\"\n)\n\nfunc Example_cleartextKeysetInBinary() {\n\t// Generate a new keyset handle for the primitive we want to use.\n\thandle, err := keyset.NewHandle(aead.AES256GCMKeyTemplate())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Serialize the keyset.\n\tbuff := &bytes.Buffer{}\n\terr = insecurecleartextkeyset.Write(handle, keyset.NewBinaryWriter(buff))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tserializedKeyset := buff.Bytes()\n\n\t// serializedKeyset can now be stored at a secure location.\n\t// WARNING: Storing the keyset in cleartext to disk is not recommended!\n\n\t// Parse the keyset.\n\tparsedHandle, err := insecurecleartextkeyset.Read(\n\t\tkeyset.NewBinaryReader(bytes.NewBuffer(serializedKeyset)))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Get the primitive.\n\tprimitive, err := aead.New(parsedHandle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Use the primitive.\n\tplaintext := []byte(\"message\")\n\tassociatedData := []byte(\"example encryption\")\n\tciphertext, err := primitive.Encrypt(plaintext, associatedData)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdecrypted, err := primitive.Decrypt(ciphertext, associatedData)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(string(decrypted))\n\t// Output: message\n}\nhttps://github.com/tink-crypto/tink-go/blob/4460d314f3fe2637bbece1db4c935b85da5660c6/insecurecleartextkeyset/example_test.go#L18-L74\n```\n\n\u003cbr /\u003e\n\n### Python\n\n\n```go\n\"\"\"A command-line utility for generating, storing and using cleartext AES128_GCM keysets.\n\nIt loads cleartext keys from disk - this is not recommended!\n\"\"\"\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport tink\nfrom tink import aead\nfrom tink import secret_key_access\n\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_enum('mode', None, ['generate', 'encrypt', 'decrypt'],\n 'The operation to perform.')\nflags.DEFINE_string('keyset_path', None,\n 'Path to the keyset used for encryption.')\nflags.DEFINE_string('input_path', None, 'Path to the input file.')\nflags.DEFINE_string('output_path', None, 'Path to the output file.')\n\n\ndef main(argv):\n del argv # Unused.\n\n # Initialise Tink\n aead.register()\n\n if FLAGS.mode == 'generate':\n # Generate a new keyset\n try:\n key_template = aead.aead_key_templates.AES128_GCM\n keyset_handle = tink.new_keyset_handle(key_template)\n except tink.TinkError as e:\n logging.exception('Error creating primitive: %s', e)\n return 1\n\n with open(FLAGS.keyset_path, 'wt') as keyset_file:\n try:\n serialized_keyset = tink.json_proto_keyset_format.serialize(\n keyset_handle, secret_key_access.TOKEN\n )\n keyset_file.write(serialized_keyset)\n except tink.TinkError as e:\n logging.exception('Error writing key: %s', e)\n return 1\n return 0\n\n # Use the input keyset to encrypt/decrypt data\n\n # Read the keyset into a keyset_handle\n with open(FLAGS.keyset_path, 'rt') as keyset_file:\n try:\n serialized_keyset = keyset_file.read()\n keyset_handle = tink.json_proto_keyset_format.parse(\n serialized_keyset, secret_key_access.TOKEN\n )\n except tink.TinkError as e:\n logging.exception('Error reading key: %s', e)\n return 1\n\n # Get the primitive\n try:\n cipher = keyset_handle.primitive(aead.Aead)\n except tink.TinkError as e:\n logging.error('Error creating primitive: %s', e)\n return 1\n\n with open(FLAGS.input_path, 'rb') as input_file:\n input_data = input_file.read()\n if FLAGS.mode == 'decrypt':\n output_data = cipher.decrypt(input_data, b'envelope_example')\n elif FLAGS.mode == 'encrypt':\n output_data = cipher.encrypt(input_data, b'envelope_example')\n else:\n logging.error(\n 'Error mode not supported. Please choose \"encrypt\" or \"decrypt\".')\n return 1\n\n with open(FLAGS.output_path, 'wb') as output_file:\n output_file.write(output_data)\n\nif __name__ == '__main__':\n flags.mark_flags_as_required(['mode', 'keyset_path'])\n app.run(main)https://github.com/tink-crypto/tink-py/blob/b87d90933ee8544875b33aee67602c5bf2013543/examples/cleartext_keyset/cleartext_keyset_cli.py#L15-L104\n```\n\n\u003cbr /\u003e"]]