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

The following examples show how to use com.google.cloud.kms.v1.KeyManagementServiceClient. 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: 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 #2
Source File: CreateKeyAsymmetricSign.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void createKeyAsymmetricSign(
    String projectId, String locationId, String keyRingId, String id) 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.
    KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

    // Build the asymmetric key to create.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256))
            .build();

    // Create the key.
    CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
    System.out.printf("Created asymmetric key %s%n", createdKey.getName());
  }
}
 
Example #3
Source File: CreateKeyRing.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void createKeyRing(String projectId, String locationId, String id) 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 and location.
    LocationName locationName = LocationName.of(projectId, locationId);

    // Build the key ring to create.
    KeyRing keyRing = KeyRing.newBuilder().build();

    // Create the key ring.
    KeyRing createdKeyRing = client.createKeyRing(locationName, id, keyRing);
    System.out.printf("Created key ring %s%n", createdKeyRing.getName());
  }
}
 
Example #4
Source File: GetPublicKey.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void getPublicKey(
    String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
    throws IOException, GeneralSecurityException {
  // 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.
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

    // Get the public key.
    PublicKey publicKey = client.getPublicKey(keyVersionName);
    System.out.printf("Public key: %s%n", publicKey.getPem());
  }
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
Source File: DecryptAsymmetric.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void decryptAsymmetric(
    String projectId,
    String locationId,
    String keyRingId,
    String keyId,
    String keyVersionId,
    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, key,
    // and key version.
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

    // Decrypt the ciphertext.
    AsymmetricDecryptResponse response =
        client.asymmetricDecrypt(keyVersionName, ByteString.copyFrom(ciphertext));
    System.out.printf("Plaintext: %s%n", response.getPlaintext().toStringUtf8());
  }
}
 
Example #10
Source File: CreateKeySymmetricEncryptDecrypt.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void createKeySymmetricEncryptDecrypt(
    String projectId, String locationId, String keyRingId, String id) 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.
    KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

    // Build the symmetric key to create.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
            .build();

    // Create the key.
    CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
    System.out.printf("Created symmetric key %s%n", createdKey.getName());
  }
}
 
Example #11
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void afterAll() throws IOException {
  Assert.assertFalse("missing GOOGLE_CLOUD_PROJECT", Strings.isNullOrEmpty(PROJECT_ID));

  // Iterate over each key ring's key's crypto key versions and destroy.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    for (CryptoKey key : client.listCryptoKeys(getKeyRingName()).iterateAll()) {
      if (key.hasRotationPeriod() || key.hasNextRotationTime()) {
        CryptoKey keyWithoutRotation = CryptoKey.newBuilder().setName(key.getName()).build();
        FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");
        client.updateCryptoKey(keyWithoutRotation, fieldMask);
      }

      ListCryptoKeyVersionsRequest listVersionsRequest =
          ListCryptoKeyVersionsRequest.newBuilder()
              .setParent(key.getName())
              .setFilter("state != DESTROYED AND state != DESTROY_SCHEDULED")
              .build();
      for (CryptoKeyVersion version :
          client.listCryptoKeyVersions(listVersionsRequest).iterateAll()) {
        client.destroyCryptoKeyVersion(version.getName());
      }
    }
  }
}
 
Example #12
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static CryptoKey createAsymmetricDecryptKey(String keyId) throws IOException {
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ASYMMETRIC_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256)
                    .build())
            .putLabels("foo", "bar")
            .putLabels("zip", "zap")
            .build();
    CryptoKey createdKey = client.createCryptoKey(getKeyRingName(), keyId, key);
    return createdKey;
  }
}
 
Example #13
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static CryptoKey createAsymmetricSignEcKey(String keyId) throws IOException {
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256)
                    .build())
            .putLabels("foo", "bar")
            .putLabels("zip", "zap")
            .build();
    CryptoKey createdKey = client.createCryptoKey(getKeyRingName(), keyId, key);
    return createdKey;
  }
}
 
Example #14
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static CryptoKey createAsymmetricSignRsaKey(String keyId) throws IOException {
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_SIGN_PSS_2048_SHA256)
                    .build())
            .putLabels("foo", "bar")
            .putLabels("zip", "zap")
            .build();
    CryptoKey createdKey = client.createCryptoKey(getKeyRingName(), keyId, key);
    return createdKey;
  }
}
 
Example #15
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static CryptoKey createHsmKey(String keyId) throws IOException {
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION)
                    .setProtectionLevel(ProtectionLevel.HSM)
                    .build())
            .putLabels("foo", "bar")
            .putLabels("zip", "zap")
            .build();
    CryptoKey createdKey = client.createCryptoKey(getKeyRingName(), keyId, key);
    return createdKey;
  }
}
 
Example #16
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static CryptoKey createSymmetricKey(String keyId) throws IOException {
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION)
                    .build())
            .putLabels("foo", "bar")
            .putLabels("zip", "zap")
            .build();
    CryptoKey createdKey = client.createCryptoKey(getKeyRingName(), keyId, key);
    return createdKey;
  }
}
 
Example #17
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 #18
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 #19
Source File: DestroyKeyVersion.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void destroyKeyVersion(
    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 key version name from the project, location, key ring, key,
    // and key version.
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

    // Destroy the key version.
    CryptoKeyVersion response = client.destroyCryptoKeyVersion(keyVersionName);
    System.out.printf("Destroyed key version: %s%n", response.getName());
  }
}
 
Example #20
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 #21
Source File: CreateKeyAsymmetricDecrypt.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void createKeyAsymmetricDecrypt(
    String projectId, String locationId, String keyRingId, String id) 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.
    KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

    // Build the asymmetric key to create.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ASYMMETRIC_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256))
            .build();

    // Create the key.
    CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
    System.out.printf("Created asymmetric key %s%n", createdKey.getName());
  }
}
 
Example #22
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 #23
Source File: KMSEncryptedNestedValueProvider.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/** Uses the GCP KMS client to decrypt an encrypted value using a KMS key of the form
 *  projects/{gcp_project}/locations/{key_region}/keyRings/{key_ring}/cryptoKeys/{kms_key_name}
 *  The encrypted value should be a base64 encrypted string which has been encrypted using
 *  the KMS encrypt API call.
 *  See <a href="https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys/encrypt">
 *  this KMS API Encrypt Link</a>.
 */
private static String decryptWithKMS(String encryptedValue, String kmsKey) throws IOException {
  /*
  kmsKey should be in the following format:
  projects/{gcp_project}/locations/{key_region}/keyRings/{key_ring}/cryptoKeys/{kms_key_name}
   */

  byte[] cipherText = Base64.getDecoder().decode(encryptedValue.getBytes("UTF-8"));


  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

    // Decrypt the ciphertext with Cloud KMS.
    DecryptResponse response = client.decrypt(kmsKey, ByteString.copyFrom(cipherText));

    // Extract the plaintext from the response.
    return new String(response.getPlaintext().toByteArray());
  }
}
 
Example #24
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void quickstart(String projectId, String locationId) 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 from the project and location.
    LocationName parent = LocationName.of(projectId, locationId);

    // Call the API.
    ListKeyRingsPagedResponse response = client.listKeyRings(parent);

    // Iterate over each key ring and print its name.
    System.out.println("key rings:");
    for (KeyRing keyRing : response.iterateAll()) {
      System.out.printf("%s%n", keyRing.getName());
    }
  }
}
 
Example #25
Source File: CreateKeyLabels.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void createKeyLabels(String projectId, String locationId, String keyRingId, String id)
    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.
    KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

    // Build the key to create with labels.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
            .putLabels("team", "alpha")
            .putLabels("cost_center", "cc1234")
            .build();

    // Create the key.
    CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
    System.out.printf("Created key with labels %s%n", createdKey.getName());
  }
}
 
Example #26
Source File: RestoreKeyVersion.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void restoreKeyVersion(
    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 key version name from the project, location, key ring, key,
    // and key version.
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

    // Restore the key version.
    CryptoKeyVersion response = client.restoreCryptoKeyVersion(keyVersionName);
    System.out.printf("Restored key version: %s%n", response.getName());
  }
}
 
Example #27
Source File: CreateKeyHsm.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void createKeyHsm(String projectId, String locationId, String keyRingId, String id)
    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.
    KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

    // Build the hsm key to create.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setProtectionLevel(ProtectionLevel.HSM)
                    .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
            .build();

    // Create the key.
    CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
    System.out.printf("Created hsm key %s%n", createdKey.getName());
  }
}
 
Example #28
Source File: EncryptAsymmetric.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void encryptAsymmetric(
    String projectId,
    String locationId,
    String keyRingId,
    String keyId,
    String keyVersionId,
    String plaintext)
    throws IOException, GeneralSecurityException {
  // 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.
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

    // Get the public key.
    PublicKey publicKey = client.getPublicKey(keyVersionName);

    // Convert the public PEM key to a DER key (see helper below).
    byte[] derKey = convertPemToDer(publicKey.getPem());
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(derKey);
    java.security.PublicKey rsaKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);

    // Encrypt plaintext for the 'RSA_DECRYPT_OAEP_2048_SHA256' key.
    // For other key algorithms:
    // https://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
    OAEPParameterSpec oaepParams =
        new OAEPParameterSpec(
            "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
    cipher.init(Cipher.ENCRYPT_MODE, rsaKey, oaepParams);
    byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
    System.out.printf("Ciphertext: %s%n", ciphertext);
  }
}
 
Example #29
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecryptAsymmetric() throws IOException, GeneralSecurityException {
  String plaintext = "my message";
  byte[] ciphertext;

  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(
            PROJECT_ID, LOCATION_ID, KEY_RING_ID, ASYMMETRIC_DECRYPT_KEY_ID, "1");
    PublicKey publicKey = client.getPublicKey(keyVersionName);

    byte[] derKey = convertPemToDer(publicKey.getPem());
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(derKey);
    java.security.PublicKey rsaKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);

    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
    OAEPParameterSpec oaepParams =
        new OAEPParameterSpec(
            "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
    cipher.init(Cipher.ENCRYPT_MODE, rsaKey, oaepParams);
    ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
  }

  new DecryptAsymmetric()
      .decryptAsymmetric(
          PROJECT_ID, LOCATION_ID, KEY_RING_ID, ASYMMETRIC_DECRYPT_KEY_ID, "1", ciphertext);
  assertThat(stdOut.toString()).contains("my message");
}
 
Example #30
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));
  }
}