Gerar uma chave de criptografia
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Gerar uma chave de criptografia.
Mais informações
Para ver a documentação detalhada que inclui este exemplo de código, consulte:
Exemplo de código
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],[],[],[],null,["Generate an encryption key.\n\nExplore further\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\nC++\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\nC#\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\nGo\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\nJava\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\nNode.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\nPHP\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\nPython\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\nRuby\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\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=storage)."]]