com.google.cloud.kms.v1.CryptoKeyName Java Examples

The following examples show how to use com.google.cloud.kms.v1.CryptoKeyName. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UpdateKeySetPrimary.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void updateKeySetPrimary(
    String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, key ring, and keyId.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Create the key.
    CryptoKey createdKey = client.updateCryptoKeyPrimaryVersion(cryptoKeyName, keyVersionId);
    System.out.printf("Updated key primary version %s%n", createdKey.getName());
  }
}
 
Example #2
Source File: CreateKeyVersion.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void createKeyVersion(String projectId, String locationId, String keyRingId, String keyId)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the parent name from the project, location, and key ring.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Build the key version to create.
    CryptoKeyVersion keyVersion = CryptoKeyVersion.newBuilder().build();

    // Create the key.
    CryptoKeyVersion createdVersion = client.createCryptoKeyVersion(cryptoKeyName, keyVersion);
    System.out.printf("Created key version %s%n", createdVersion.getName());
  }
}
 
Example #3
Source File: GetKeyLabels.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void getKeyLabels(String projectId, String locationId, String keyRingId, String keyId)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, key ring, and keyId.
    CryptoKeyName keyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Get the key.
    CryptoKey key = client.getCryptoKey(keyName);

    // Print out each label.
    key.getLabelsMap().forEach((k, v) -> System.out.printf("%s=%s%n", k, v));
  }
}
 
Example #4
Source File: EncryptSymmetric.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void encryptSymmetric(
    String projectId, String locationId, String keyRingId, String keyId, String plaintext)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // 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 keyVersionName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Encrypt the plaintext.
    EncryptResponse response = client.encrypt(keyVersionName, ByteString.copyFromUtf8(plaintext));
    System.out.printf("Ciphertext: %s%n", response.getCiphertext().toStringUtf8());
  }
}
 
Example #5
Source File: UpdateKeyRemoveRotation.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void updateKeyRemoveRotation(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, key ring, and keyId.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Build an empty key with no labels.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setName(cryptoKeyName.toString())
            .clearRotationPeriod()
            .clearNextRotationTime()
            .build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

    // Create the key.
    CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", createdKey.getName());
  }
}
 
Example #6
Source File: DecryptSymmetric.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void decryptSymmetric(
    String projectId, String locationId, String keyRingId, String keyId, byte[] ciphertext)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the key version name from the project, location, key ring, and
    // key.
    CryptoKeyName keyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Decrypt the response.
    DecryptResponse response = client.decrypt(keyName, ByteString.copyFrom(ciphertext));
    System.out.printf("Plaintext: %s%n", response.getPlaintext().toStringUtf8());
  }
}
 
Example #7
Source File: UpdateKeyRemoveLabels.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void updateKeyRemoveLabels(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, key ring, and keyId.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Build an empty key with no labels.
    CryptoKey key = CryptoKey.newBuilder().setName(cryptoKeyName.toString()).build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("labels");

    // Create the key.
    CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", createdKey.getName());
  }
}
 
Example #8
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static CryptoKeyVersion createKeyVersion(String keyId)
    throws IOException, InterruptedException, TimeoutException {
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKeyName keyName = CryptoKeyName.of(PROJECT_ID, LOCATION_ID, KEY_RING_ID, keyId);
    CryptoKeyVersion keyVersion = CryptoKeyVersion.newBuilder().build();
    CryptoKeyVersion createdVersion = client.createCryptoKeyVersion(keyName, keyVersion);

    for (int i = 1; i <= 5; i++) {
      CryptoKeyVersion gotVersion = client.getCryptoKeyVersion(createdVersion.getName());
      if (gotVersion.getState() == CryptoKeyVersionState.ENABLED) {
        return gotVersion;
      }

      Thread.sleep(500 * i);
    }

    throw new TimeoutException("key version not ready in timeout");
  }
}
 
Example #9
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecryptSymmetric() throws IOException {
  String plaintext = "my plaintext";
  byte[] ciphertext;

  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKeyName keyName =
        CryptoKeyName.of(PROJECT_ID, LOCATION_ID, KEY_RING_ID, SYMMETRIC_KEY_ID);
    EncryptResponse result = client.encrypt(keyName, ByteString.copyFromUtf8(plaintext));
    ciphertext = result.getCiphertext().toByteArray();
  }

  new DecryptSymmetric()
      .decryptSymmetric(PROJECT_ID, LOCATION_ID, KEY_RING_ID, SYMMETRIC_KEY_ID, ciphertext);
  assertThat(stdOut.toString()).contains(plaintext);
}
 
Example #10
Source File: KeyStoreIntegrationTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Ensure KMS permissions are configured as expected. This ensures a key ring
 * and crypto key exist. It then fetches the public key associated to the
 * crypto key and encodes a small string. Then the KMS api is called to
 * decrypt the message. This test (and following tests) require Cloud KMS
 * Admin, CryptoKey Decrypter, and Public Key Viewer.
 */
@Test
public void testKmsConfigured() throws Exception {
  // encrypt a realistically sized payload
  byte[] plainText = Resources
      .toByteArray(Resources.getResource("pioneer/study-foo.private.json"));
  String cryptoKeyId = "test-kms-configured";
  String resourceId = CryptoKeyName.of(projectId, "global", keyRingId, cryptoKeyId).toString();
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    ensureKmsResources(client, resourceId);
    byte[] cipherText = encrypt(client, resourceId, plainText);
    byte[] decrypted = decrypt(client, resourceId, cipherText);
    assertEquals(new String(plainText), new String(decrypted));
  }
}
 
Example #11
Source File: UpdateKeyUpdateLabels.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void updateKeyUpdateLabels(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the parent name from the project, location, and key ring.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    //
    // Step 1 - get the current set of labels on the key
    //

    // Get the current key.
    CryptoKey key = client.getCryptoKey(cryptoKeyName);

    //
    // Step 2 - add a label to the list of labels
    //

    // Add a new label.
    key = key.toBuilder().putLabels("new_label", "new_value").build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("labels");

    // Update the key.
    CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", updatedKey.getName());
  }
}
 
Example #12
Source File: IamAddMember.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void iamAddMember(
    String projectId, String locationId, String keyRingId, String keyId, String member)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // 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());
  }
}
 
Example #13
Source File: IamRemoveMember.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void iamRemoveMember(
    String projectId, String locationId, String keyRingId, String keyId, String member)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // 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);

    // Search through the bindings and remove matches.
    String roleToFind = "roles/cloudkms.cryptoKeyEncrypterDecrypter";
    for (Binding binding : policy.getBindingsList()) {
      if (binding.getRole().equals(roleToFind) && binding.getMembersList().contains(member)) {
        binding.getMembersList().remove(member);
      }
    }

    client.setIamPolicy(resourceName, policy);
    System.out.printf("Updated IAM policy for %s%n", resourceName.toString());
  }
}
 
Example #14
Source File: UpdateKeyAddRotation.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void updateKeyAddRotation(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, and key ring.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Calculate the date 24 hours from now (this is used below).
    long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

    // Build the key to update with a rotation schedule.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setName(cryptoKeyName.toString())
            .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))

            // Rotate every 30 days.
            .setRotationPeriod(
                Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))

            // Start the first rotation in 24 hours.
            .setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
            .build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

    // Update the key.
    CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", updatedKey.getName());
  }
}
 
Example #15
Source File: IamGetPolicy.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void iamGetPolicy(String projectId, String locationId, String keyRingId, String keyId)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // 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);
      }
    }
  }
}