packagecleartextkeyset;import staticjava.nio.charset.StandardCharsets.UTF_8;importcom.google.crypto.tink.Aead;importcom.google.crypto.tink.InsecureSecretKeyAccess;importcom.google.crypto.tink.KeysetHandle;importcom.google.crypto.tink.RegistryConfiguration;importcom.google.crypto.tink.TinkJsonProtoKeysetFormat;importcom.google.crypto.tink.aead.AeadConfig;importcom.google.crypto.tink.aead.PredefinedAeadParameters;importjava.nio.file.Files;importjava.nio.file.Path;importjava.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. */publicfinalclassCleartextKeysetExample{privatestaticfinalStringMODE_ENCRYPT="encrypt";privatestaticfinalStringMODE_DECRYPT="decrypt";privatestaticfinalStringMODE_GENERATE="generate";privatestaticfinalbyte[]EMPTY_ASSOCIATED_DATA=newbyte[0];publicstaticvoidmain(String[]args)throwsException{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);}Stringmode=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);}PathkeyFile=Paths.get(args[1]);// Initialise Tink: register all AEAD key types with the Tink runtimeAeadConfig.register();if(MODE_GENERATE.equals(mode)){KeysetHandlehandle=KeysetHandle.generateNew(PredefinedAeadParameters.AES128_GCM);StringserializedKeyset=TinkJsonProtoKeysetFormat.serializeKeyset(handle,InsecureSecretKeyAccess.get());Files.write(keyFile,serializedKeyset.getBytes(UTF_8));return;}// Use the primitive to encrypt/decrypt files// Read the keyset from diskStringserializedKeyset=newString(Files.readAllBytes(keyFile),UTF_8);KeysetHandlehandle=TinkJsonProtoKeysetFormat.parseKeyset(serializedKeyset,InsecureSecretKeyAccess.get());// Get the primitiveAeadaead=handle.getPrimitive(RegistryConfiguration.get(),Aead.class);byte[]input=Files.readAllBytes(Paths.get(args[2]));PathoutputFile=Paths.get(args[3]);if(MODE_ENCRYPT.equals(mode)){byte[]ciphertext=aead.encrypt(input,EMPTY_ASSOCIATED_DATA);Files.write(outputFile,ciphertext);}elseif(MODE_DECRYPT.equals(mode)){byte[]plaintext=aead.decrypt(input,EMPTY_ASSOCIATED_DATA);Files.write(outputFile,plaintext);}}privateCleartextKeysetExample(){}}
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")funcExample_cleartextKeysetInBinary(){// Generate a new keyset handle for the primitive we want to use.handle,err:=keyset.NewHandle(aead.AES256GCMKeyTemplate())iferr!=nil{log.Fatal(err)}// Serialize the keyset.buff:=&bytes.Buffer{}err=insecurecleartextkeyset.Write(handle,keyset.NewBinaryWriter(buff))iferr!=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)))iferr!=nil{log.Fatal(err)}// Get the primitive.primitive,err:=aead.New(parsedHandle)iferr!=nil{log.Fatal(err)}// Use the primitive.plaintext:=[]byte("message")associatedData:=[]byte("example encryption")ciphertext,err:=primitive.Encrypt(plaintext,associatedData)iferr!=nil{log.Fatal(err)}decrypted,err:=primitive.Decrypt(ciphertext,associatedData)iferr!=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!"""fromabslimportappfromabslimportflagsfromabslimportloggingimporttinkfromtinkimportaeadfromtinkimportsecret_key_accessFLAGS=flags.FLAGSflags.DEFINE_enum('mode',None,['generate','encrypt','decrypt'],'Theoperationtoperform.')flags.DEFINE_string('keyset_path',None,'Pathtothekeysetusedforencryption.')flags.DEFINE_string('input_path',None,'Pathtotheinputfile.')flags.DEFINE_string('output_path',None,'Pathtotheoutputfile.')defmain(argv):delargv#Unused.#InitialiseTinkaead.register()ifFLAGS.mode=='generate':#Generateanewkeysettry:key_template=aead.aead_key_templates.AES128_GCMkeyset_handle=tink.new_keyset_handle(key_template)excepttink.TinkErrorase:logging.exception('Errorcreatingprimitive:%s',e)return1withopen(FLAGS.keyset_path,'wt')askeyset_file:try:serialized_keyset=tink.json_proto_keyset_format.serialize(keyset_handle,secret_key_access.TOKEN)keyset_file.write(serialized_keyset)excepttink.TinkErrorase:logging.exception('Errorwritingkey:%s',e)return1return0#Usetheinputkeysettoencrypt/decryptdata#Readthekeysetintoakeyset_handlewithopen(FLAGS.keyset_path,'rt')askeyset_file:try:serialized_keyset=keyset_file.read()keyset_handle=tink.json_proto_keyset_format.parse(serialized_keyset,secret_key_access.TOKEN)excepttink.TinkErrorase:logging.exception('Errorreadingkey:%s',e)return1#Gettheprimitivetry:cipher=keyset_handle.primitive(aead.Aead)excepttink.TinkErrorase:logging.error('Errorcreatingprimitive:%s',e)return1withopen(FLAGS.input_path,'rb')asinput_file:input_data=input_file.read()ifFLAGS.mode=='decrypt':output_data=cipher.decrypt(input_data,b'envelope_example')elifFLAGS.mode=='encrypt':output_data=cipher.encrypt(input_data,b'envelope_example')else:logging.error('Errormodenotsupported.Pleasechoose"encrypt"or"decrypt".')return1withopen(FLAGS.output_path,'wb')asoutput_file:output_file.write(output_data)if__name__=='__main__':flags.mark_flags_as_required(['mode','keyset_path'])app.run(main)
[null,null,["2025-07-25 UTC-তে শেষবার আপডেট করা হয়েছে।"],[[["\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"]]