Genera una chiave di crittografia

Genera una chiave di crittografia.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// Create a pseudo-random number generator (PRNG), this is included for
// demonstration purposes only. You should consult your security team about
// best practices to initialize PRNG. In particular, you should verify that
// the C++ library and operating system provide enough entropy to meet the
// security policies in your organization.

// Use the Mersenne-Twister Engine in this example:
//   https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
// Any C++ PRNG can be used below, the choice is arbitrary.
using GeneratorType = std::mt19937_64;

// Create the default random device to fetch entropy.
std::random_device rd;

// Compute how much entropy we need to initialize the GeneratorType:
constexpr auto kRequiredEntropyWords =
    GeneratorType::state_size *
    (GeneratorType::word_size / std::numeric_limits<unsigned int>::digits);

// Capture the entropy bits into a vector.
std::vector<std::uint64_t> entropy(kRequiredEntropyWords);
std::generate(entropy.begin(), entropy.end(), [&rd] { return rd(); });

// Create the PRNG with the fetched entropy.
std::seed_seq seed(entropy.begin(), entropy.end());

// initialized with enough entropy such that the encryption keys are not
// predictable. Note that the default constructor for all the generators in
// the C++ standard library produce predictable keys.
std::mt19937_64 gen(seed);

namespace gcs = ::google::cloud::storage;
gcs::EncryptionKeyData data = gcs::CreateKeyFromGenerator(gen);

std::cout << "Base64 encoded key = " << data.key << "\n"
          << "Base64 encoded SHA256 of key = " << data.sha256 << "\n";

C#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


using Google.Cloud.Storage.V1;
using System;

public class GenerateEncryptionKeySample
{
    public string GenerateEncryptionKey()
    {
        var encryptionKey = EncryptionKey.Generate().Base64Key;
        Console.WriteLine($"Generated Base64-encoded AES-256 encryption key: {encryptionKey}");
        return encryptionKey;
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
)

// generateEncryptionKey generates a 256 bit (32 byte) AES encryption key and
// prints the base64 representation.
func generateEncryptionKey(w io.Writer) error {
	// This is included for demonstration purposes. You should generate your own
	// key. Please remember that encryption keys should be handled with a
	// comprehensive security policy.
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		return fmt.Errorf("rand.Read: %w", err)
	}
	encryptionKey := base64.StdEncoding.EncodeToString(key)
	fmt.Fprintf(w, "Generated base64-encoded encryption key: %v\n", encryptionKey)
	return nil
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


import com.google.common.io.BaseEncoding;
import java.security.SecureRandom;

public class GenerateEncryptionKey {
  /**
   * Generates a 256 bit (32 byte) AES encryption key and prints the base64 representation. This is
   * included for demonstration purposes only. You should generate your own key, and consult your
   * security team about best practices. Please remember that encryption keys should be handled with
   * a comprehensive security policy.
   */
  public static void generateEncryptionKey() {
    byte[] key = new byte[32];
    new SecureRandom().nextBytes(key);
    String encryptionKey = BaseEncoding.base64().encode(key);

    System.out.println("Generated Base64-encoded AES-256 encryption key: " + encryptionKey);
  }
}

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

const crypto = require('crypto');

function generateEncryptionKey() {
  /**
   * Generates a 256 bit (32 byte) AES encryption key and prints the base64
   * representation.
   *
   * This is included for demonstration purposes. You should generate your own
   * key. Please remember that encryption keys should be handled with a
   * comprehensive security policy.
   */
  const buffer = crypto.randomBytes(32);
  const encodedKey = buffer.toString('base64');
  console.log(`Base 64 encoded encryption key: ${encodedKey}`);
}
generateEncryptionKey();

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


/**
 * Generate a base64 encoded encryption key for Google Cloud Storage.
 */
function generate_encryption_key(): void
{
    $key = random_bytes(32);
    $encodedKey = base64_encode($key);
    printf('Your encryption key: %s' . PHP_EOL, $encodedKey);
}

Python

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import base64
import os

def generate_encryption_key():
    """Generates a 256 bit (32 byte) AES encryption key and prints the
    base64 representation.

    This is included for demonstration purposes. You should generate your own
    key. Please remember that encryption keys should be handled with a
    comprehensive security policy.
    """
    key = os.urandom(32)
    encoded_key = base64.b64encode(key).decode("utf-8")

    print(f"Base 64 encoded encryption key: {encoded_key}")

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

def generate_encryption_key
  # Generates a 256 bit (32 byte) AES encryption key and prints the base64 representation.
  #
  # This is included for demonstration purposes. You should generate your own key.
  # Please remember that encryption keys should be handled with a comprehensive security policy.
  require "base64"
  require "openssl"

  encryption_key  = OpenSSL::Cipher.new("aes-256-cfb").encrypt.random_key
  encoded_enc_key = Base64.encode64 encryption_key

  puts "Sample encryption key: #{encoded_enc_key}"
end

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.