Search in sources :

Example 41 with KeyManagementServiceClient

use of com.google.cloud.kms.v1.KeyManagementServiceClient in project gcp-ingestion by mozilla.

the class KeyStoreIntegrationTest method prepareKeyStoreMetadata.

/**
 * Upload a metadata file and the referenced private keys to their testing
 * locations. The resource is a templated metadata json file. "DUMMY_*"
 * variables are replaced with their corresponding locations. This also
 * encrypts the private keys and ensures that the KMS resources are created if
 * specified.
 */
private String prepareKeyStoreMetadata(String resource, boolean shouldEncrypt) throws Exception {
    // enable gs support
    FileSystems.setDefaultPipelineOptions(PipelineOptionsFactory.create());
    byte[] data = Resources.toByteArray(Resources.getResource(resource));
    ArrayNode nodes = Json.readArrayNode(data);
    for (JsonNode node : nodes) {
        // replace dummy values with values related to integration testing
        String kmsResourceId = node.get("kms_resource_id").textValue().replace("DUMMY_PROJECT_ID", projectId);
        // The path may be on the local filesystem or in cloud storage by
        // referencing a variable to be replaced.
        String privateKeyUri = node.get("private_key_uri").textValue().replace("DUMMY_BUCKET", bucket).replace("DUMMY_TEMP_FOLDER", tempFolder.getRoot().toString());
        ((ObjectNode) node).put("kms_resource_id", kmsResourceId);
        ((ObjectNode) node).put("private_key_uri", privateKeyUri);
        String privateKeyId = node.get("private_key_id").textValue();
        byte[] key = Resources.toByteArray(Resources.getResource(String.format("pioneer/%s.private.json", privateKeyId)));
        // optionally encrypt the private key resources and upload to testing location
        if (shouldEncrypt) {
            try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
                ensureKmsResources(client, kmsResourceId);
                byte[] encryptedKey = encrypt(client, kmsResourceId, key);
                writeToStorage(privateKeyUri, encryptedKey);
            }
        } else {
            writeToStorage(privateKeyUri, key);
        }
    }
    assertFalse(nodes.asText().contains("DUMMY_PROJECT_ID") || nodes.asText().contains("DUMMY_BUCKET") || nodes.asText().contains("DUMMY_TEMP_FOLDER"));
    String keyStoreMetadata = String.format("gs://%s/metadata.json", bucket);
    writeToStorage(keyStoreMetadata, nodes.toString().getBytes("UTF-8"));
    return keyStoreMetadata;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ByteString(com.google.protobuf.ByteString) KeyManagementServiceClient(com.google.cloud.kms.v1.KeyManagementServiceClient)

Example 42 with KeyManagementServiceClient

use of com.google.cloud.kms.v1.KeyManagementServiceClient in project java-docs-samples by GoogleCloudPlatform.

the class EncryptSymmetric method encryptSymmetric.

// Encrypt data with a given key.
public void encryptSymmetric(String projectId, String locationId, String keyRingId, String keyId, String plaintext) throws IOException {
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
        // Build the key name from the project, location, key ring, and key.
        CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);
        // Convert plaintext to ByteString.
        ByteString plaintextByteString = ByteString.copyFromUtf8(plaintext);
        // Optional, but recommended: compute plaintext's CRC32C. See helper below.
        long plaintextCrc32c = getCrc32cAsLong(plaintextByteString.toByteArray());
        // Encrypt the plaintext.
        EncryptRequest request = EncryptRequest.newBuilder().setName(cryptoKeyName.toString()).setPlaintext(plaintextByteString).setPlaintextCrc32C(Int64Value.newBuilder().setValue(plaintextCrc32c).build()).build();
        EncryptResponse response = client.encrypt(request);
        // https://cloud.google.com/kms/docs/data-integrity-guidelines
        if (!response.getVerifiedPlaintextCrc32C()) {
            throw new IOException("Encrypt: request to server corrupted");
        }
        // See helper below.
        if (!crcMatches(response.getCiphertextCrc32C().getValue(), response.getCiphertext().toByteArray())) {
            throw new IOException("Encrypt: response from server corrupted");
        }
        System.out.printf("Ciphertext: %s%n", response.getCiphertext().toStringUtf8());
    }
}
Also used : EncryptResponse(com.google.cloud.kms.v1.EncryptResponse) CryptoKeyName(com.google.cloud.kms.v1.CryptoKeyName) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) KeyManagementServiceClient(com.google.cloud.kms.v1.KeyManagementServiceClient) EncryptRequest(com.google.cloud.kms.v1.EncryptRequest)

Example 43 with KeyManagementServiceClient

use of com.google.cloud.kms.v1.KeyManagementServiceClient in project java-docs-samples by GoogleCloudPlatform.

the class GetKeyVersionAttestation method getKeyVersionAttestation.

// Get the attestations for a key version
public void getKeyVersionAttestation(String projectId, String locationId, String keyRingId, String keyId, String keyVersionId) throws IOException {
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
        // Build the name from the project, location, key ring, and keyId.
        CryptoKeyVersionName keyVersionName = CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);
        // Get the key version.
        CryptoKeyVersion keyVersion = client.getCryptoKeyVersion(keyVersionName);
        // will be nil.
        if (!keyVersion.hasAttestation()) {
            System.out.println("no attestation");
            return;
        }
        // Print the attestation, base64-encoded.
        KeyOperationAttestation attestation = keyVersion.getAttestation();
        String format = attestation.getFormat().toString();
        byte[] content = attestation.getContent().toByteArray();
        System.out.printf("%s: %s", format, Base64.getEncoder().encodeToString(content));
    }
}
Also used : CryptoKeyVersionName(com.google.cloud.kms.v1.CryptoKeyVersionName) KeyOperationAttestation(com.google.cloud.kms.v1.KeyOperationAttestation) CryptoKeyVersion(com.google.cloud.kms.v1.CryptoKeyVersion) KeyManagementServiceClient(com.google.cloud.kms.v1.KeyManagementServiceClient)

Example 44 with KeyManagementServiceClient

use of com.google.cloud.kms.v1.KeyManagementServiceClient in project java-docs-samples by GoogleCloudPlatform.

the class IamAddMember method iamAddMember.

// Add the given IAM member to the key.
public void iamAddMember(String projectId, String locationId, String keyRingId, String keyId, String member) throws IOException {
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
        // Build the key version name from the project, location, key ring, key,
        // and key version.
        CryptoKeyName resourceName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);
        // The resource name could also be a key ring.
        // KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);
        // Get the current policy.
        Policy policy = client.getIamPolicy(resourceName);
        // Create a new IAM binding for the member and role.
        Binding binding = Binding.newBuilder().setRole("roles/cloudkms.cryptoKeyEncrypterDecrypter").addMembers(member).build();
        // Add the binding to the policy.
        Policy newPolicy = policy.toBuilder().addBindings(binding).build();
        client.setIamPolicy(resourceName, newPolicy);
        System.out.printf("Updated IAM policy for %s%n", resourceName.toString());
    }
}
Also used : Policy(com.google.iam.v1.Policy) Binding(com.google.iam.v1.Binding) CryptoKeyName(com.google.cloud.kms.v1.CryptoKeyName) KeyManagementServiceClient(com.google.cloud.kms.v1.KeyManagementServiceClient)

Example 45 with KeyManagementServiceClient

use of com.google.cloud.kms.v1.KeyManagementServiceClient in project java-docs-samples by GoogleCloudPlatform.

the class IamGetPolicy method iamGetPolicy.

// Get the IAM policy for the given key.
public void iamGetPolicy(String projectId, String locationId, String keyRingId, String keyId) throws IOException {
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
        // Build the key version name from the project, location, key ring, key,
        // and key version.
        CryptoKeyName resourceName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);
        // The resource name could also be a key ring.
        // KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);
        // Get the current policy.
        Policy policy = client.getIamPolicy(resourceName);
        // Print the policy.
        System.out.printf("IAM policy:%n");
        for (Binding binding : policy.getBindingsList()) {
            System.out.printf("%s%n", binding.getRole());
            for (String member : binding.getMembersList()) {
                System.out.printf("- %s%n", member);
            }
        }
    }
}
Also used : Policy(com.google.iam.v1.Policy) Binding(com.google.iam.v1.Binding) CryptoKeyName(com.google.cloud.kms.v1.CryptoKeyName) KeyManagementServiceClient(com.google.cloud.kms.v1.KeyManagementServiceClient)

Aggregations

KeyManagementServiceClient (com.google.cloud.kms.v1.KeyManagementServiceClient)185 CryptoKey (com.google.cloud.kms.v1.CryptoKey)56 CryptoKeyVersion (com.google.cloud.kms.v1.CryptoKeyVersion)39 CryptoKeyVersionName (com.google.cloud.kms.v1.CryptoKeyVersionName)37 CryptoKeyName (com.google.cloud.kms.v1.CryptoKeyName)33 ByteString (com.google.protobuf.ByteString)20 KeyRingName (com.google.cloud.kms.v1.KeyRingName)17 KeyRing (com.google.cloud.kms.v1.KeyRing)16 FieldMask (com.google.protobuf.FieldMask)16 PublicKey (com.google.cloud.kms.v1.PublicKey)14 ImportJob (com.google.cloud.kms.v1.ImportJob)10 Test (org.junit.Test)10 Digest (com.google.cloud.kms.v1.Digest)8 EncryptResponse (com.google.cloud.kms.v1.EncryptResponse)8 Policy (com.google.iam.v1.Policy)8 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)8 DecryptResponse (com.google.cloud.kms.v1.DecryptResponse)7 AsymmetricDecryptResponse (com.google.cloud.kms.v1.AsymmetricDecryptResponse)6 AsymmetricSignResponse (com.google.cloud.kms.v1.AsymmetricSignResponse)6 LocationName (com.google.cloud.kms.v1.LocationName)6