diff --git a/privateca/cloud-client/src/main/java/privateca/CreateCaPool.java b/privateca/cloud-client/src/main/java/privateca/CreateCaPool.java new file mode 100644 index 00000000000..9a0ab28e9a8 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/CreateCaPool.java @@ -0,0 +1,80 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_create_ca_pool] + +import com.google.api.core.ApiFuture; +import com.google.cloud.security.privateca.v1.CaPool; +import com.google.cloud.security.privateca.v1.CaPool.Tier; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.CreateCaPoolRequest; +import com.google.cloud.security.privateca.v1.LocationName; +import com.google.longrunning.Operation; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class CreateCaPool { + + public static void main(String[] args) + throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: Set a unique name for the CA pool. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + createCaPool(project, location, caPoolName); + } + + // Create a Certificate Authority Pool. All certificates created under this CA pool will + // follow the same issuance policy, IAM policies,etc., + public static void createCaPool(String project, String location, String caPoolName) + throws InterruptedException, ExecutionException, 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + /* Create the pool request + Set Parent which denotes the project id and location. + Set the Tier (see: https://cloud.google.com/certificate-authority-service/docs/tiers). + */ + CreateCaPoolRequest caPoolRequest = + CreateCaPoolRequest.newBuilder() + .setParent(LocationName.of(project, location).toString()) + .setCaPoolId(caPoolName) + .setCaPool(CaPool.newBuilder().setTier(Tier.ENTERPRISE).build()) + .build(); + + // Create the CA pool. + ApiFuture futureCall = + certificateAuthorityServiceClient.createCaPoolCallable().futureCall(caPoolRequest); + Operation response = futureCall.get(); + + if (response.hasError()) { + System.out.println("Error while creating CA pool !" + response.getError()); + return; + } + + System.out.println("CA pool created successfully: " + caPoolName); + } + } +} +// [END privateca_create_ca_pool] diff --git a/privateca/cloud-client/src/main/java/privateca/CreateCertificate.java b/privateca/cloud-client/src/main/java/privateca/CreateCertificate.java new file mode 100644 index 00000000000..8be4f175bc4 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/CreateCertificate.java @@ -0,0 +1,186 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_create_certificate] + +import com.google.api.core.ApiFuture; +import com.google.cloud.kms.v1.CryptoKeyVersionName; +import com.google.cloud.kms.v1.KeyManagementServiceClient; +import com.google.cloud.security.privateca.v1.CaPoolName; +import com.google.cloud.security.privateca.v1.Certificate; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.CertificateConfig; +import com.google.cloud.security.privateca.v1.CertificateConfig.SubjectConfig; +import com.google.cloud.security.privateca.v1.CreateCertificateRequest; +import com.google.cloud.security.privateca.v1.KeyUsage; +import com.google.cloud.security.privateca.v1.KeyUsage.ExtendedKeyUsageOptions; +import com.google.cloud.security.privateca.v1.KeyUsage.KeyUsageOptions; +import com.google.cloud.security.privateca.v1.PublicKey; +import com.google.cloud.security.privateca.v1.PublicKey.KeyFormat; +import com.google.cloud.security.privateca.v1.Subject; +import com.google.cloud.security.privateca.v1.SubjectAltNames; +import com.google.cloud.security.privateca.v1.X509Parameters; +import com.google.cloud.security.privateca.v1.X509Parameters.CaOptions; +import com.google.protobuf.ByteString; +import com.google.protobuf.Duration; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class CreateCertificate { + + public static void main(String[] args) + throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + + // To sign and issue a certificate, a public key is essential. Here, we are making use + // of Cloud KMS to retrieve an already created public key. Specify the following details to + // retrieve the key. For more info, see: https://cloud.google.com/kms/docs/retrieve-public-key + String project = "your-project-id"; + String kmsLocation = "kms-location"; + String keyRingId = "your-ring-id"; + String keyId = "your-key-id"; + String keyVersionId = "your-version-id"; + + // Retrieve the public key from Cloud KMS. + ByteString publicKeyBytes = + retrievePublicKey(project, kmsLocation, keyRingId, keyId, keyVersionId); + + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: Set a unique name for the CA pool. + // certificateAuthorityName: The name of the certificate authority which issues the certificate. + // certificateName: Set a unique name for the certificate. + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + String certificateAuthorityName = "certificate-authority-name"; + String certificateName = "certificate-name"; + + createCertificate( + project, location, caPoolName, certificateAuthorityName, certificateName, publicKeyBytes); + } + + // Create a Certificate which is issued by the Certificate Authority present in the CA Pool. + // The key used to sign the certificate is created by the Cloud KMS. + public static void createCertificate( + String project, + String location, + String caPoolName, + String certificateAuthorityName, + String certificateName, + ByteString publicKeyBytes) + throws InterruptedException, ExecutionException, 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + // commonName: Enter a title for your certificate. + // orgName: Provide the name of your company. + // domainName: List the fully qualified domain name. + // certificateLifetime: The validity of the certificate in seconds. + String commonName = "common-name"; + String orgName = "org-name"; + String domainName = "dnsname.com"; + long certificateLifetime = 1000L; + + // Set the Public Key and its format as obtained from the Cloud KMS. + PublicKey publicKey = + PublicKey.newBuilder().setKey(publicKeyBytes).setFormat(KeyFormat.PEM).build(); + + SubjectConfig subjectConfig = + SubjectConfig.newBuilder() + // Set the common name and org name. + .setSubject( + Subject.newBuilder().setCommonName(commonName).setOrganization(orgName).build()) + // Set the fully qualified domain name. + .setSubjectAltName(SubjectAltNames.newBuilder().addDnsNames(domainName).build()) + .build(); + + // Set the X.509 fields required for the certificate. + X509Parameters x509Parameters = + X509Parameters.newBuilder() + .setKeyUsage( + KeyUsage.newBuilder() + .setBaseKeyUsage( + KeyUsageOptions.newBuilder() + .setDigitalSignature(true) + .setKeyEncipherment(true) + .setCertSign(true) + .build()) + .setExtendedKeyUsage( + ExtendedKeyUsageOptions.newBuilder().setServerAuth(true).build()) + .build()) + .setCaOptions(CaOptions.newBuilder().setIsCa(true).buildPartial()) + .build(); + + // Create certificate. + Certificate certificate = + Certificate.newBuilder() + .setConfig( + CertificateConfig.newBuilder() + .setPublicKey(publicKey) + .setSubjectConfig(subjectConfig) + .setX509Config(x509Parameters) + .build()) + .setLifetime(Duration.newBuilder().setSeconds(certificateLifetime).build()) + .build(); + + // Create the Certificate Request. + CreateCertificateRequest certificateRequest = + CreateCertificateRequest.newBuilder() + .setParent(CaPoolName.of(project, location, caPoolName).toString()) + .setCertificateId(certificateName) + .setCertificate(certificate) + .setIssuingCertificateAuthorityId(certificateAuthorityName) + .build(); + + // Get the Certificate response. + ApiFuture future = + certificateAuthorityServiceClient + .createCertificateCallable() + .futureCall(certificateRequest); + + Certificate response = future.get(); + // Get the PEM encoded, signed X.509 certificate. + System.out.println(response.getPemCertificate()); + // To verify the obtained certificate, use this intermediate chain list. + System.out.println(response.getPemCertificateChainList()); + } + } + + // Get the public Key used for signing the certificate from Cloud KMS. + public static ByteString retrievePublicKey( + String project, String kmsLocation, 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 `client.close()` method on the client to safely + // clean up any remaining background resources. + try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { + + CryptoKeyVersionName keyVersionName = + CryptoKeyVersionName.of(project, kmsLocation, keyRingId, keyId, keyVersionId); + com.google.cloud.kms.v1.PublicKey publicKey = client.getPublicKey(keyVersionName); + + ByteString publicKeyBytes = publicKey.getPemBytes(); + return publicKeyBytes; + } + } +} +// [END privateca_create_certificate] diff --git a/privateca/cloud-client/src/main/java/privateca/CreateCertificateAuthority.java b/privateca/cloud-client/src/main/java/privateca/CreateCertificateAuthority.java new file mode 100644 index 00000000000..b4877b90b60 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/CreateCertificateAuthority.java @@ -0,0 +1,133 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_create_ca] + +import com.google.api.core.ApiFuture; +import com.google.cloud.security.privateca.v1.CaPoolName; +import com.google.cloud.security.privateca.v1.CertificateAuthority; +import com.google.cloud.security.privateca.v1.CertificateAuthority.KeyVersionSpec; +import com.google.cloud.security.privateca.v1.CertificateAuthority.SignHashAlgorithm; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.CertificateConfig; +import com.google.cloud.security.privateca.v1.CertificateConfig.SubjectConfig; +import com.google.cloud.security.privateca.v1.CreateCertificateAuthorityRequest; +import com.google.cloud.security.privateca.v1.KeyUsage; +import com.google.cloud.security.privateca.v1.KeyUsage.KeyUsageOptions; +import com.google.cloud.security.privateca.v1.Subject; +import com.google.cloud.security.privateca.v1.X509Parameters; +import com.google.cloud.security.privateca.v1.X509Parameters.CaOptions; +import com.google.longrunning.Operation; +import com.google.protobuf.Duration; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class CreateCertificateAuthority { + + public static void main(String[] args) + throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: Set it to the CA Pool under which the CA should be created. + // certificateAuthorityName: Unique name for the CA. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + String certificateAuthorityName = "certificate-authority-name"; + createCertificateAuthority(project, location, caPoolName, certificateAuthorityName); + } + + // Create Certificate Authority which is the root CA in the given CA Pool. This CA will be + // responsible for signing certificates within this pool. + public static void createCertificateAuthority( + String project, String location, String caPoolName, String certificateAuthorityName) + throws InterruptedException, ExecutionException, 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + String commonName = "common-name"; + String orgName = "org-name"; + int caDuration = 100000; // Validity of this CA in seconds. + + // Set the types of Algorithm used to create a cloud KMS key. + KeyVersionSpec keyVersionSpec = + KeyVersionSpec.newBuilder().setAlgorithm(SignHashAlgorithm.RSA_PKCS1_4096_SHA256).build(); + + // Set CA subject config. + SubjectConfig subjectConfig = + SubjectConfig.newBuilder() + .setSubject( + Subject.newBuilder().setCommonName(commonName).setOrganization(orgName).build()) + .build(); + + // Set the key usage options for X.509 fields. + X509Parameters x509Parameters = + X509Parameters.newBuilder() + .setKeyUsage( + KeyUsage.newBuilder() + .setBaseKeyUsage( + KeyUsageOptions.newBuilder().setCrlSign(true).setCertSign(true).build()) + .build()) + .setCaOptions(CaOptions.newBuilder().setIsCa(true).build()) + .build(); + + // Set certificate authority settings. + CertificateAuthority certificateAuthority = + CertificateAuthority.newBuilder() + // CertificateAuthority.Type.SELF_SIGNED denotes that this CA is a root CA. + .setType(CertificateAuthority.Type.SELF_SIGNED) + .setKeySpec(keyVersionSpec) + .setConfig( + CertificateConfig.newBuilder() + .setSubjectConfig(subjectConfig) + .setX509Config(x509Parameters) + .build()) + // Set the CA validity duration. + .setLifetime(Duration.newBuilder().setSeconds(caDuration).build()) + .build(); + + // Create the CertificateAuthorityRequest. + CreateCertificateAuthorityRequest certificateAuthorityRequest = + CreateCertificateAuthorityRequest.newBuilder() + .setParent(CaPoolName.of(project, location, caPoolName).toString()) + .setCertificateAuthorityId(certificateAuthorityName) + .setCertificateAuthority(certificateAuthority) + .build(); + + // Create Certificate Authority. + ApiFuture futureCall = + certificateAuthorityServiceClient + .createCertificateAuthorityCallable() + .futureCall(certificateAuthorityRequest); + Operation response = futureCall.get(); + + if (response.hasError()) { + System.out.println("Error while creating CA !" + response.getError()); + return; + } + + System.out.println( + "Certificate Authority created successfully : " + certificateAuthorityName); + } + } +} +// [END privateca_create_ca] diff --git a/privateca/cloud-client/src/main/java/privateca/DeleteCaPool.java b/privateca/cloud-client/src/main/java/privateca/DeleteCaPool.java new file mode 100644 index 00000000000..69e0a12a380 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/DeleteCaPool.java @@ -0,0 +1,80 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_delete_ca_pool] + +import com.google.api.core.ApiFuture; +import com.google.cloud.security.privateca.v1.CaPoolName; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.DeleteCaPoolRequest; +import com.google.longrunning.Operation; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +public class DeleteCaPool { + + public static void main(String[] args) + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: The name of the CA pool to be deleted. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + deleteCaPool(project, location, caPoolName); + } + + // Delete the CA pool as mentioned by the caPoolName. + // Before deleting the pool, all CAs in the pool MUST BE deleted. + public static void deleteCaPool(String project, String location, String caPoolName) + throws InterruptedException, ExecutionException, 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + // Set the project, location and caPoolName to delete. + CaPoolName caPool = + CaPoolName.newBuilder() + .setProject(project) + .setLocation(location) + .setCaPool(caPoolName) + .build(); + + // Create the Delete request. + DeleteCaPoolRequest deleteCaPoolRequest = + DeleteCaPoolRequest.newBuilder().setName(caPool.toString()).build(); + + // Delete the CA Pool. + ApiFuture futureCall = + certificateAuthorityServiceClient.deleteCaPoolCallable().futureCall(deleteCaPoolRequest); + Operation response = futureCall.get(); + + if (response.hasError()) { + System.out.println("Error while deleting CA pool !" + response.getError()); + return; + } + + System.out.println("Deleted CA Pool: " + caPoolName); + } + } +} +// [END privateca_delete_ca_pool] diff --git a/privateca/cloud-client/src/main/java/privateca/DeleteCertificateAuthority.java b/privateca/cloud-client/src/main/java/privateca/DeleteCertificateAuthority.java new file mode 100644 index 00000000000..d370acf8306 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/DeleteCertificateAuthority.java @@ -0,0 +1,113 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_delete_ca] + +import com.google.api.core.ApiFuture; +import com.google.cloud.security.privateca.v1.CertificateAuthority.State; +import com.google.cloud.security.privateca.v1.CertificateAuthorityName; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.DeleteCertificateAuthorityRequest; +import com.google.longrunning.Operation; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class DeleteCertificateAuthority { + + public static void main(String[] args) + throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: The name of the CA pool under which the CA is present. + // certificateAuthorityName: The name of the CA to be deleted. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + String certificateAuthorityName = "certificate-authority-name"; + deleteCertificateAuthority(project, location, caPoolName, certificateAuthorityName); + } + + // Delete the Certificate Authority from the specified CA pool. + // Before deletion, the CA must be disabled and must not contain any active certificates. + public static void deleteCertificateAuthority( + String project, String location, String caPoolName, String certificateAuthorityName) + throws IOException, ExecutionException, InterruptedException { + // 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + // Create the Certificate Authority Name. + CertificateAuthorityName certificateAuthorityNameParent = + CertificateAuthorityName.newBuilder() + .setProject(project) + .setLocation(location) + .setCaPool(caPoolName) + .setCertificateAuthority(certificateAuthorityName) + .build(); + + // Check if the CA is enabled. + State caState = + certificateAuthorityServiceClient + .getCertificateAuthority(certificateAuthorityNameParent) + .getState(); + if (caState == State.ENABLED) { + System.out.println( + "Please disable the Certificate Authority before deletion ! Current state: " + caState); + return; + } + + // Create the DeleteCertificateAuthorityRequest. + // Setting the setIgnoreActiveCertificates() to true, will delete the CA + // even if it contains active certificates. Care should be taken to re-anchor + // the certificates to new CA before deleting. + DeleteCertificateAuthorityRequest deleteCertificateAuthorityRequest = + DeleteCertificateAuthorityRequest.newBuilder() + .setName(certificateAuthorityNameParent.toString()) + .setIgnoreActiveCertificates(false) + .build(); + + // Delete the Certificate Authority. + ApiFuture futureCall = + certificateAuthorityServiceClient + .deleteCertificateAuthorityCallable() + .futureCall(deleteCertificateAuthorityRequest); + Operation response = futureCall.get(); + + if (response.hasError()) { + System.out.println("Error while deleting Certificate Authority !" + response.getError()); + return; + } + + // Check if the CA has been deleted. + caState = + certificateAuthorityServiceClient + .getCertificateAuthority(certificateAuthorityNameParent) + .getState(); + if (caState == State.DELETED) { + System.out.println( + "Successfully deleted Certificate Authority : " + certificateAuthorityName); + } else { + System.out.println( + "Unable to delete Certificate Authority. Please try again ! Current state: " + caState); + } + } + } +} +// [END privateca_delete_ca] diff --git a/privateca/cloud-client/src/main/java/privateca/DisableCertificateAuthority.java b/privateca/cloud-client/src/main/java/privateca/DisableCertificateAuthority.java new file mode 100644 index 00000000000..73ab2cf1163 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/DisableCertificateAuthority.java @@ -0,0 +1,99 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_disable_ca] + +import com.google.api.core.ApiFuture; +import com.google.cloud.security.privateca.v1.CertificateAuthority.State; +import com.google.cloud.security.privateca.v1.CertificateAuthorityName; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.DisableCertificateAuthorityRequest; +import com.google.longrunning.Operation; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class DisableCertificateAuthority { + + public static void main(String[] args) + throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: The name of the CA pool under which the CA is present. + // certificateAuthorityName: The name of the CA to be disabled. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + String certificateAuthorityName = "certificate-authority-name"; + disableCertificateAuthority(project, location, caPoolName, certificateAuthorityName); + } + + // Disable a Certificate Authority which is present in the given CA pool. + public static void disableCertificateAuthority( + String project, String location, String caPoolName, String certificateAuthorityName) + throws IOException, ExecutionException, InterruptedException { + // 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + // Create the Certificate Authority Name. + CertificateAuthorityName certificateAuthorityNameParent = + CertificateAuthorityName.newBuilder() + .setProject(project) + .setLocation(location) + .setCaPool(caPoolName) + .setCertificateAuthority(certificateAuthorityName) + .build(); + + // Create the Disable Certificate Authority Request. + DisableCertificateAuthorityRequest disableCertificateAuthorityRequest = + DisableCertificateAuthorityRequest.newBuilder() + .setName(certificateAuthorityNameParent.toString()) + .build(); + + // Disable the Certificate Authority. + ApiFuture futureCall = + certificateAuthorityServiceClient + .disableCertificateAuthorityCallable() + .futureCall(disableCertificateAuthorityRequest); + Operation response = futureCall.get(); + + if (response.hasError()) { + System.out.println("Error while disabling Certificate Authority !" + response.getError()); + return; + } + + // Get the current CA state. + State caState = + certificateAuthorityServiceClient + .getCertificateAuthority(certificateAuthorityNameParent) + .getState(); + + // Check if the Certificate Authority is disabled. + if (caState == State.DISABLED) { + System.out.println("Disabled Certificate Authority : " + certificateAuthorityName); + } else { + System.out.println( + "Cannot disable the Certificate Authority ! Current CA State: " + caState); + } + } + } +} +// [END privateca_disable_ca] diff --git a/privateca/cloud-client/src/main/java/privateca/EnableCertificateAuthority.java b/privateca/cloud-client/src/main/java/privateca/EnableCertificateAuthority.java new file mode 100644 index 00000000000..121d7998b77 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/EnableCertificateAuthority.java @@ -0,0 +1,95 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_enable_ca] + +import com.google.api.core.ApiFuture; +import com.google.cloud.security.privateca.v1.CertificateAuthority.State; +import com.google.cloud.security.privateca.v1.CertificateAuthorityName; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.EnableCertificateAuthorityRequest; +import com.google.longrunning.Operation; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class EnableCertificateAuthority { + + public static void main(String[] args) + throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: The name of the CA pool under which the CA is present. + // certificateAuthorityName: The name of the CA to be enabled. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + String certificateAuthorityName = "certificate-authority-name"; + enableCertificateAuthority(project, location, caPoolName, certificateAuthorityName); + } + + // Enable the Certificate Authority present in the given ca pool. + // CA cannot be enabled if it has been already deleted. + public static void enableCertificateAuthority( + String project, String location, String caPoolName, String certificateAuthorityName) + throws IOException, ExecutionException, InterruptedException { + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + // Create the Certificate Authority Name. + CertificateAuthorityName certificateAuthorityParent = + CertificateAuthorityName.newBuilder() + .setProject(project) + .setLocation(location) + .setCaPool(caPoolName) + .setCertificateAuthority(certificateAuthorityName) + .build(); + + // Create the Enable Certificate Authority Request. + EnableCertificateAuthorityRequest enableCertificateAuthorityRequest = + EnableCertificateAuthorityRequest.newBuilder() + .setName(certificateAuthorityParent.toString()) + .build(); + + // Enable the Certificate Authority. + ApiFuture futureCall = + certificateAuthorityServiceClient + .enableCertificateAuthorityCallable() + .futureCall(enableCertificateAuthorityRequest); + Operation response = futureCall.get(); + + if (response.hasError()) { + System.out.println("Error while enabling Certificate Authority !" + response.getError()); + return; + } + + // Get the current CA state. + State caState = + certificateAuthorityServiceClient + .getCertificateAuthority(certificateAuthorityParent) + .getState(); + + // Check if the CA is enabled. + if (caState == State.ENABLED) { + System.out.println("Enabled Certificate Authority : " + certificateAuthorityName); + } else { + System.out.println( + "Cannot enable the Certificate Authority ! Current CA State: " + caState); + } + } + } +} +// [END privateca_enable_ca] diff --git a/privateca/cloud-client/src/main/java/privateca/ListCaPools.java b/privateca/cloud-client/src/main/java/privateca/ListCaPools.java new file mode 100644 index 00000000000..aec8ff4e134 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/ListCaPools.java @@ -0,0 +1,65 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_list_ca_pool] + +import com.google.cloud.security.privateca.v1.CaPool; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.LocationName; +import java.io.IOException; + +public class ListCaPools { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + String project = "your-project-id"; + String location = "ca-location"; + listCaPools(project, location); + } + + // List all CA pools present in the given project and location. + public static void listCaPools(String project, String location) 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + // Set the Location Name which contains project and location of the pool. + LocationName locationName = + LocationName.newBuilder().setProject(project).setLocation(location).build(); + + String caPoolName = ""; + System.out.println("Available CA pools: "); + + // List the CA pools. + for (CaPool caPool : + certificateAuthorityServiceClient.listCaPools(locationName).iterateAll()) { + caPoolName = caPool.getName(); + // caPoolName represents the full resource name of the + // format 'projects/{project-id}/locations/{location}/ca-pools/{ca-pool-name}'. + // Hence stripping it down to just pool name. + System.out.println( + caPoolName.substring(caPoolName.lastIndexOf("/") + 1) + " " + caPool.isInitialized()); + } + } + } +} +// [END privateca_list_ca_pool] diff --git a/privateca/cloud-client/src/main/java/privateca/ListCertificateAuthorities.java b/privateca/cloud-client/src/main/java/privateca/ListCertificateAuthorities.java new file mode 100644 index 00000000000..49d76dfb875 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/ListCertificateAuthorities.java @@ -0,0 +1,65 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_list_ca] + +import com.google.cloud.security.privateca.v1.CaPoolName; +import com.google.cloud.security.privateca.v1.CertificateAuthority; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import java.io.IOException; + +public class ListCertificateAuthorities { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: The name of the CA pool under which the CAs to be listed are present. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + listCertificateAuthority(project, location, caPoolName); + } + + // List all Certificate authorities present in the given CA Pool. + public static void listCertificateAuthority(String project, String location, String caPoolName) + 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + // Create CA pool name comprising of project, location and the pool name. + CaPoolName parent = + CaPoolName.newBuilder() + .setProject(project) + .setLocation(location) + .setCaPool(caPoolName) + .build(); + + // List the CA name and its corresponding state. + for (CertificateAuthority certificateAuthority : + certificateAuthorityServiceClient.listCertificateAuthorities(parent).iterateAll()) { + System.out.println( + certificateAuthority.getName() + " is " + certificateAuthority.getState()); + } + } + } +} +// [END privateca_list_ca] diff --git a/privateca/cloud-client/src/main/java/privateca/ListCertificates.java b/privateca/cloud-client/src/main/java/privateca/ListCertificates.java new file mode 100644 index 00000000000..1e255c21bb2 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/ListCertificates.java @@ -0,0 +1,64 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_list_certificate] + +import com.google.cloud.security.privateca.v1.CaPoolName; +import com.google.cloud.security.privateca.v1.Certificate; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import java.io.IOException; + +public class ListCertificates { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: Name of the CA pool which contains the certificates to be listed. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + listCertificates(project, location, caPoolName); + } + + // List Certificates present in the given CA pool. + public static void listCertificates(String project, String location, String caPoolName) + 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + CaPoolName caPool = + CaPoolName.newBuilder() + .setProject(project) + .setLocation(location) + .setCaPool(caPoolName) + .build(); + + // Retrieve and print the certificate names. + System.out.println("Available certificates: "); + for (Certificate certificate : + certificateAuthorityServiceClient.listCertificates(caPool).iterateAll()) { + System.out.println(certificate.getName()); + } + } + } +} +// [END privateca_list_certificate] diff --git a/privateca/cloud-client/src/main/java/privateca/RevokeCertificate.java b/privateca/cloud-client/src/main/java/privateca/RevokeCertificate.java new file mode 100644 index 00000000000..c12171ca1f9 --- /dev/null +++ b/privateca/cloud-client/src/main/java/privateca/RevokeCertificate.java @@ -0,0 +1,84 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +// [START privateca_revoke_certificate] + +import com.google.api.core.ApiFuture; +import com.google.cloud.security.privateca.v1.Certificate; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.CertificateName; +import com.google.cloud.security.privateca.v1.RevocationReason; +import com.google.cloud.security.privateca.v1.RevokeCertificateRequest; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class RevokeCertificate { + + public static void main(String[] args) + throws IOException, ExecutionException, InterruptedException { + // TODO(developer): Replace these variables before running the sample. + // location: For a list of locations, see: + // https://cloud.google.com/certificate-authority-service/docs/locations + // caPoolName: Name for the CA pool which contains the certificate. + // certificateName: Name of the certificate to be revoked. + String project = "your-project-id"; + String location = "ca-location"; + String caPoolName = "ca-pool-name"; + String certificateName = "certificate-name"; + revokeCertificate(project, location, caPoolName, certificateName); + } + + // Revoke an issued certificate. Once revoked, the certificate will become invalid and will expire + // post its lifetime. + public static void revokeCertificate( + String project, String location, String caPoolName, String certificateName) + throws IOException, ExecutionException, InterruptedException { + // 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 `certificateAuthorityServiceClient.close()` method on the client to safely + // clean up any remaining background resources. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + + // Create Certificate Name. + CertificateName certificateNameParent = + CertificateName.newBuilder() + .setProject(project) + .setLocation(location) + .setCaPool(caPoolName) + .setCertificate(certificateName) + .build(); + + // Create Revoke Certificate Request and specify the appropriate revocation reason. + RevokeCertificateRequest revokeCertificateRequest = + RevokeCertificateRequest.newBuilder() + .setName(certificateNameParent.toString()) + .setReason(RevocationReason.PRIVILEGE_WITHDRAWN) + .build(); + + // Revoke certificate. + ApiFuture response = + certificateAuthorityServiceClient + .revokeCertificateCallable() + .futureCall(revokeCertificateRequest); + Certificate certificateResponse = response.get(); + + System.out.println("Certificate Revoked: " + certificateResponse.getName()); + } + } +} +// [END privateca_revoke_certificate] diff --git a/privateca/cloud-client/src/test/java/privateca/SnippetsIT.java b/privateca/cloud-client/src/test/java/privateca/SnippetsIT.java new file mode 100644 index 00000000000..6764556402a --- /dev/null +++ b/privateca/cloud-client/src/test/java/privateca/SnippetsIT.java @@ -0,0 +1,322 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package privateca; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.cloud.kms.v1.CreateKeyRingRequest; +import com.google.cloud.kms.v1.CryptoKey; +import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose; +import com.google.cloud.kms.v1.CryptoKeyVersion; +import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm; +import com.google.cloud.kms.v1.CryptoKeyVersionName; +import com.google.cloud.kms.v1.CryptoKeyVersionTemplate; +import com.google.cloud.kms.v1.KeyManagementServiceClient; +import com.google.cloud.kms.v1.KeyRing; +import com.google.cloud.kms.v1.KeyRingName; +import com.google.cloud.kms.v1.LocationName; +import com.google.cloud.security.privateca.v1.CaPoolName; +import com.google.cloud.security.privateca.v1.Certificate; +import com.google.cloud.security.privateca.v1.CertificateAuthority; +import com.google.cloud.security.privateca.v1.CertificateAuthorityName; +import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient; +import com.google.cloud.security.privateca.v1.CertificateName; +import com.google.protobuf.ByteString; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class SnippetsIT { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION; + private static String KMS_LOCATION; + private static String CA_POOL_NAME; + private static String CA_POOL_NAME_DELETE; + private static String CA_NAME; + private static String CA_NAME_DELETE; + private static String CERTIFICATE_NAME; + private static String KEY_RING_ID; + private static String KEY_ID; + private static String VERSION_ID; + + private ByteArrayOutputStream stdOut; + + // Check if the required environment variables are set. + public static void reqEnvVar(String envVarName) { + assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) + .that(System.getenv(envVarName)) + .isNotEmpty(); + } + + @BeforeClass + public static void setUp() throws InterruptedException, ExecutionException, IOException { + reqEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + reqEnvVar("GOOGLE_CLOUD_PROJECT"); + + LOCATION = "asia-south1"; + KMS_LOCATION = "global"; + CA_POOL_NAME = "ca-pool-" + UUID.randomUUID().toString(); + CA_POOL_NAME_DELETE = "ca-pool-" + UUID.randomUUID().toString(); + CA_NAME = "ca-name-" + UUID.randomUUID().toString(); + CA_NAME_DELETE = "ca-name-" + UUID.randomUUID().toString(); + CERTIFICATE_NAME = "certificate-name-" + UUID.randomUUID().toString(); + KEY_RING_ID = "key-ring-id-" + UUID.randomUUID().toString(); + KEY_ID = "key-id-" + UUID.randomUUID().toString(); + VERSION_ID = "1"; + + // Create CA Pool. + privateca.CreateCaPool.createCaPool(PROJECT_ID, LOCATION, CA_POOL_NAME); + privateca.CreateCaPool.createCaPool(PROJECT_ID, LOCATION, CA_POOL_NAME_DELETE); + + // Create and Enable Certificate Authorities. + privateca.CreateCertificateAuthority.createCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME); + privateca.CreateCertificateAuthority.createCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME_DELETE); + sleep(10); + privateca.EnableCertificateAuthority.enableCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME); + + // Create Asymmetric Sign Key used to sign certificate, with Cloud KMS. + createKeyRing(); + sleep(5); + createAsymmetricSignKey(); + + // Retrieve public key from Cloud KMS and Create Certificate. + ByteString publicKey = + privateca.CreateCertificate.retrievePublicKey( + PROJECT_ID, KMS_LOCATION, KEY_RING_ID, KEY_ID, VERSION_ID); + privateca.CreateCertificate.createCertificate( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME, CERTIFICATE_NAME, publicKey); + sleep(5); + } + + @AfterClass + public static void cleanUp() throws InterruptedException, ExecutionException, IOException { + + ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + + // De-provision public key. + cleanupCertificateSignKey(); + + // Delete CA and CA pool. + privateca.DeleteCertificateAuthority.deleteCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME); + sleep(5); + privateca.DeleteCaPool.deleteCaPool(PROJECT_ID, LOCATION, CA_POOL_NAME); + + stdOut = null; + System.setOut(null); + } + + // Create a new key ring. + public static void createKeyRing() 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(PROJECT_ID, KMS_LOCATION); + + // Build the key ring to create. + KeyRing keyRing = KeyRing.newBuilder().setName(locationName.toString()).build(); + + // Create the key ring. + KeyRing createdKeyRing = + client.createKeyRing( + CreateKeyRingRequest.newBuilder() + .setParent(locationName.toString()) + .setKeyRing(keyRing) + .setKeyRingId(KEY_RING_ID) + .build()); + System.out.printf("Created key ring: %s%n", createdKeyRing.getName()); + } + } + + // Create a new asymmetric key for the purpose of signing and verifying data. + public static void createAsymmetricSignKey() 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(PROJECT_ID, KMS_LOCATION, KEY_RING_ID); + + // 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, KEY_ID, key); + System.out.printf("Created asymmetric key: %s%n", createdKey.getName()); + } + } + + public static void cleanupCertificateSignKey() throws IOException, InterruptedException { + try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { + CryptoKeyVersionName cryptoKeyVersionName = + CryptoKeyVersionName.of(PROJECT_ID, KMS_LOCATION, KEY_RING_ID, KEY_ID, VERSION_ID); + // Destroy the crypto key version. + CryptoKeyVersion cryptoKeyVersion = client.destroyCryptoKeyVersion(cryptoKeyVersionName); + sleep(5); + // If the response has destroy time, then the version is successfully destroyed. + Assert.assertTrue(cryptoKeyVersion.hasDestroyTime()); + } + } + + // Wait for the specified amount of time. + public static void sleep(int seconds) throws InterruptedException { + TimeUnit.SECONDS.sleep(seconds); + } + + @Before + public void beforeEach() { + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void afterEach() { + stdOut = null; + System.setOut(null); + } + + @Test + public void testCreateCAPool() throws IOException { + // Check if the CA pool created during setup is successful. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + String caPoolName = + certificateAuthorityServiceClient + .getCaPool(CaPoolName.of(PROJECT_ID, LOCATION, CA_POOL_NAME).toString()) + .getName(); + assertThat(caPoolName) + .contains( + String.format( + "projects/%s/locations/%s/caPools/%s", PROJECT_ID, LOCATION, CA_POOL_NAME)); + } + } + + @Test + public void testListCAPools() throws IOException { + privateca.ListCaPools.listCaPools(PROJECT_ID, LOCATION); + assertThat(stdOut.toString()).contains(CA_POOL_NAME); + } + + @Test + public void testDeleteCAPool() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + privateca.DeleteCaPool.deleteCaPool(PROJECT_ID, LOCATION, CA_POOL_NAME_DELETE); + assertThat(stdOut.toString()).contains("Deleted CA Pool: " + CA_POOL_NAME_DELETE); + } + + @Test + public void testCreateCertificateAuthority() throws IOException { + // Check if the CA created during setup is successful. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + CertificateAuthority response = + certificateAuthorityServiceClient.getCertificateAuthority( + CertificateAuthorityName.of(PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME).toString()); + assertThat(response.getName()).contains(CA_NAME); + } + } + + @Test + public void testListCertificateAuthorities() throws IOException { + privateca.ListCertificateAuthorities.listCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME); + assertThat(stdOut.toString()).contains(CA_NAME); + } + + @Test + public void testEnableDisableCertificateAuthority() + throws InterruptedException, ExecutionException, IOException { + privateca.EnableCertificateAuthority.enableCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME); + assertThat(stdOut.toString()).contains("Enabled Certificate Authority : " + CA_NAME); + privateca.DisableCertificateAuthority.disableCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME); + assertThat(stdOut.toString()).contains("Disabled Certificate Authority : " + CA_NAME); + } + + @Test + public void testDeleteCertificateAuthority() + throws InterruptedException, ExecutionException, IOException { + privateca.DeleteCertificateAuthority.deleteCertificateAuthority( + PROJECT_ID, LOCATION, CA_POOL_NAME, CA_NAME_DELETE); + assertThat(stdOut.toString()) + .contains("Successfully deleted Certificate Authority : " + CA_NAME_DELETE); + } + + @Test + public void testCreateCertificate() throws IOException { + // Check if the certificate created during setup is successful. + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + CertificateName certificateName = + CertificateName.of(PROJECT_ID, LOCATION, CA_POOL_NAME, CERTIFICATE_NAME); + Certificate certificate = certificateAuthorityServiceClient.getCertificate(certificateName); + assertThat(certificate.getName()).contains(CERTIFICATE_NAME); + } + } + + @Test + public void testListCertificates() throws IOException { + privateca.ListCertificates.listCertificates(PROJECT_ID, LOCATION, CA_POOL_NAME); + assertThat(stdOut.toString()).contains(CERTIFICATE_NAME); + } + + @Test + public void testRevokeCertificate() throws InterruptedException, ExecutionException, IOException { + try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = + CertificateAuthorityServiceClient.create()) { + // Revoke the certificate. + privateca.RevokeCertificate.revokeCertificate( + PROJECT_ID, LOCATION, CA_POOL_NAME, CERTIFICATE_NAME); + + // Check if the certificate has revocation details. If it does, then the certificate is + // considered as revoked. + CertificateName certificateName = + CertificateName.of(PROJECT_ID, LOCATION, CA_POOL_NAME, CERTIFICATE_NAME); + Assert.assertTrue( + certificateAuthorityServiceClient.getCertificate(certificateName).hasRevocationDetails()); + } + } +} diff --git a/privateca/pom.xml b/privateca/pom.xml index e8607b3bf1e..62902c21208 100644 --- a/privateca/pom.xml +++ b/privateca/pom.xml @@ -1,4 +1,16 @@ + 4.0.0 com.google.cloud @@ -23,6 +35,18 @@ UTF-8 + + + + com.google.cloud + libraries-bom + 20.7.0 + pom + import + + + + @@ -31,6 +55,11 @@ 1.0.0 + + com.google.cloud + google-cloud-kms + + junit junit