Generar una clave de encriptación
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Generar una clave de encriptación
Explora más
Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:
Muestra de código
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],[],[],[],null,["# Generate an encryption key.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Use customer-supplied encryption keys](/storage/docs/encryption/using-customer-supplied-keys)\n\nCode sample\n-----------\n\n### C++\n\n\nFor more information, see the\n[Cloud Storage C++ API\nreference documentation](/cpp/docs/reference/storage/latest).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n // Create a pseudo-random number generator (PRNG), this is included for\n // demonstration purposes only. You should consult your security team about\n // best practices to initialize PRNG. In particular, you should verify that\n // the C++ library and operating system provide enough entropy to meet the\n // security policies in your organization.\n\n // Use the Mersenne-Twister Engine in this example:\n // https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine\n // Any C++ PRNG can be used below, the choice is arbitrary.\n using GeneratorType = std::mt19937_64;\n\n // Create the default random device to fetch entropy.\n std::random_device rd;\n\n // Compute how much entropy we need to initialize the GeneratorType:\n constexpr auto kRequiredEntropyWords =\n GeneratorType::state_size *\n (GeneratorType::word_size / std::numeric_limits\u003cunsigned int\u003e::digits);\n\n // Capture the entropy bits into a vector.\n std::vector\u003cstd::uint64_t\u003e entropy(kRequiredEntropyWords);\n std::generate(entropy.begin(), entropy.end(), [&rd] { return rd(); });\n\n // Create the PRNG with the fetched entropy.\n std::seed_seq seed(entropy.begin(), entropy.end());\n\n // initialized with enough entropy such that the encryption keys are not\n // predictable. Note that the default constructor for all the generators in\n // the C++ standard library produce predictable keys.\n std::mt19937_64 gen(seed);\n\n namespace gcs = ::google::cloud::storage;\n gcs::EncryptionKeyData data = gcs::CreateKeyFromGenerator(gen);\n\n std::cout \u003c\u003c \"Base64 encoded key = \" \u003c\u003c data.key \u003c\u003c \"\\n\"\n \u003c\u003c \"Base64 encoded SHA256 of key = \" \u003c\u003c data.sha256 \u003c\u003c \"\\n\";\n\n### C#\n\n\nFor more information, see the\n[Cloud Storage C# API\nreference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n\n using https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.html;\n using System;\n\n public class GenerateEncryptionKeySample\n {\n public string GenerateEncryptionKey()\n {\n var encryptionKey = https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.EncryptionKey.html.https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.EncryptionKey.html#Google_Cloud_Storage_V1_EncryptionKey_Generate().https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.EncryptionKey.html#Google_Cloud_Storage_V1_EncryptionKey_Base64Key;\n Console.WriteLine($\"Generated Base64-encoded AES-256 encryption key: {encryptionKey}\");\n return encryptionKey;\n }\n }\n\n### Go\n\n\nFor more information, see the\n[Cloud Storage Go API\nreference documentation](https://pkg.go.dev/cloud.google.com/go/storage).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n import (\n \t\"crypto/rand\"\n \t\"encoding/base64\"\n \t\"fmt\"\n \t\"io\"\n )\n\n // generateEncryptionKey generates a 256 bit (32 byte) AES encryption key and\n // prints the base64 representation.\n func generateEncryptionKey(w io.Writer) error {\n \t// This is included for demonstration purposes. You should generate your own\n \t// key. Please remember that encryption keys should be handled with a\n \t// comprehensive security policy.\n \tkey := make([]byte, 32)\n \tif _, err := rand.Read(key); err != nil {\n \t\treturn fmt.Errorf(\"rand.Read: %w\", err)\n \t}\n \tencryptionKey := base64.StdEncoding.EncodeToString(key)\n \tfmt.Fprintf(w, \"Generated base64-encoded encryption key: %v\\n\", encryptionKey)\n \treturn nil\n }\n\n### Java\n\n\nFor more information, see the\n[Cloud Storage Java API\nreference documentation](https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/overview).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n\n import com.google.common.io.BaseEncoding;\n import java.security.SecureRandom;\n\n public class GenerateEncryptionKey {\n /**\n * Generates a 256 bit (32 byte) AES encryption key and prints the base64 representation. This is\n * included for demonstration purposes only. You should generate your own key, and consult your\n * security team about best practices. Please remember that encryption keys should be handled with\n * a comprehensive security policy.\n */\n public static void generateEncryptionKey() {\n byte[] key = new byte[32];\n new SecureRandom().nextBytes(key);\n String encryptionKey = BaseEncoding.base64().encode(key);\n\n System.out.println(\"Generated Base64-encoded AES-256 encryption key: \" + encryptionKey);\n }\n }\n\n### Node.js\n\n\nFor more information, see the\n[Cloud Storage Node.js API\nreference documentation](https://cloud.google.com/nodejs/docs/reference/storage/latest).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n const crypto = require('crypto');\n\n function generateEncryptionKey() {\n /**\n * Generates a 256 bit (32 byte) AES encryption key and prints the base64\n * representation.\n *\n * This is included for demonstration purposes. You should generate your own\n * key. Please remember that encryption keys should be handled with a\n * comprehensive security policy.\n */\n const buffer = crypto.randomBytes(32);\n const encodedKey = buffer.toString('base64');\n console.log(`Base 64 encoded encryption key: ${encodedKey}`);\n }\n generateEncryptionKey();\n\n### PHP\n\n\nFor more information, see the\n[Cloud Storage PHP API\nreference documentation](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/storage/storageclient).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n\n /**\n * Generate a base64 encoded encryption key for Google Cloud Storage.\n */\n function generate_encryption_key(): void\n {\n $key = random_bytes(32);\n $encodedKey = base64_encode($key);\n printf('Your encryption key: %s' . PHP_EOL, $encodedKey);\n }\n\n### Python\n\n\nFor more information, see the\n[Cloud Storage Python API\nreference documentation](https://cloud.google.com/python/docs/reference/storage/latest).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n import base64\n import os\n\n\n def generate_encryption_key():\n \"\"\"Generates a 256 bit (32 byte) AES encryption key and prints the\n base64 representation.\n\n This is included for demonstration purposes. You should generate your own\n key. Please remember that encryption keys should be handled with a\n comprehensive security policy.\n \"\"\"\n key = os.urandom(32)\n encoded_key = base64.b64encode(key).decode(\"utf-8\")\n\n print(f\"Base 64 encoded encryption key: {encoded_key}\")\n\n### Ruby\n\n\nFor more information, see the\n[Cloud Storage Ruby API\nreference documentation](https://googleapis.dev/ruby/google-cloud-storage/latest/Google/Cloud/Storage.html).\n\n\nTo authenticate to Cloud Storage, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/storage/docs/authentication#client-libs).\n\n def generate_encryption_key\n # Generates a 256 bit (32 byte) AES encryption key and prints the base64 representation.\n #\n # This is included for demonstration purposes. You should generate your own key.\n # Please remember that encryption keys should be handled with a comprehensive security policy.\n require \"base64\"\n require \"openssl\"\n\n encryption_key = OpenSSL::Cipher.new(\"aes-256-cfb\").encrypt.random_key\n encoded_enc_key = Base64.encode64 encryption_key\n\n puts \"Sample encryption key: #{encoded_enc_key}\"\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=storage)."]]