Skip to content

Commit 79bf2de

Browse files
sitalakshmisgcf-owl-bot[bot]
authored andcommitted
feat: add client code samples (#203)
* init commit - code samples for private ca * Added support for LRO and included comments. * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md * docs: added comments for more context * refactor: modified ca param name to disambiguate * feat: added samples and tests to create, list and revoke certificates * chore: modified dependency to include kms * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md * refactor: improves readability * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md * refactor: added error reporting context and modified class names to align with API design * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md * docs: updated the client name in comment Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 49657f4 commit 79bf2de

13 files changed

+1415
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package privateca;
17+
18+
// [START privateca_create_ca_pool]
19+
20+
import com.google.api.core.ApiFuture;
21+
import com.google.cloud.security.privateca.v1.CaPool;
22+
import com.google.cloud.security.privateca.v1.CaPool.Tier;
23+
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
24+
import com.google.cloud.security.privateca.v1.CreateCaPoolRequest;
25+
import com.google.cloud.security.privateca.v1.LocationName;
26+
import com.google.longrunning.Operation;
27+
import java.io.IOException;
28+
import java.util.concurrent.ExecutionException;
29+
30+
public class CreateCaPool {
31+
32+
public static void main(String[] args)
33+
throws InterruptedException, ExecutionException, IOException {
34+
// TODO(developer): Replace these variables before running the sample.
35+
// location: For a list of locations, see:
36+
// https://cloud.google.com/certificate-authority-service/docs/locations
37+
// caPoolName: Set a unique name for the CA pool.
38+
String project = "your-project-id";
39+
String location = "ca-location";
40+
String caPoolName = "ca-pool-name";
41+
createCaPool(project, location, caPoolName);
42+
}
43+
44+
// Create a Certificate Authority Pool. All certificates created under this CA pool will
45+
// follow the same issuance policy, IAM policies,etc.,
46+
public static void createCaPool(String project, String location, String caPoolName)
47+
throws InterruptedException, ExecutionException, IOException {
48+
// Initialize client that will be used to send requests. This client only needs to be created
49+
// once, and can be reused for multiple requests. After completing all of your requests, call
50+
// the `certificateAuthorityServiceClient.close()` method on the client to safely
51+
// clean up any remaining background resources.
52+
try (CertificateAuthorityServiceClient certificateAuthorityServiceClient =
53+
CertificateAuthorityServiceClient.create()) {
54+
55+
/* Create the pool request
56+
Set Parent which denotes the project id and location.
57+
Set the Tier (see: https://cloud.google.com/certificate-authority-service/docs/tiers).
58+
*/
59+
CreateCaPoolRequest caPoolRequest =
60+
CreateCaPoolRequest.newBuilder()
61+
.setParent(LocationName.of(project, location).toString())
62+
.setCaPoolId(caPoolName)
63+
.setCaPool(CaPool.newBuilder().setTier(Tier.ENTERPRISE).build())
64+
.build();
65+
66+
// Create the CA pool.
67+
ApiFuture<Operation> futureCall =
68+
certificateAuthorityServiceClient.createCaPoolCallable().futureCall(caPoolRequest);
69+
Operation response = futureCall.get();
70+
71+
if (response.hasError()) {
72+
System.out.println("Error while creating CA pool !" + response.getError());
73+
return;
74+
}
75+
76+
System.out.println("CA pool created successfully: " + caPoolName);
77+
}
78+
}
79+
}
80+
// [END privateca_create_ca_pool]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package privateca;
17+
18+
// [START privateca_create_certificate]
19+
20+
import com.google.api.core.ApiFuture;
21+
import com.google.cloud.kms.v1.CryptoKeyVersionName;
22+
import com.google.cloud.kms.v1.KeyManagementServiceClient;
23+
import com.google.cloud.security.privateca.v1.CaPoolName;
24+
import com.google.cloud.security.privateca.v1.Certificate;
25+
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
26+
import com.google.cloud.security.privateca.v1.CertificateConfig;
27+
import com.google.cloud.security.privateca.v1.CertificateConfig.SubjectConfig;
28+
import com.google.cloud.security.privateca.v1.CreateCertificateRequest;
29+
import com.google.cloud.security.privateca.v1.KeyUsage;
30+
import com.google.cloud.security.privateca.v1.KeyUsage.ExtendedKeyUsageOptions;
31+
import com.google.cloud.security.privateca.v1.KeyUsage.KeyUsageOptions;
32+
import com.google.cloud.security.privateca.v1.PublicKey;
33+
import com.google.cloud.security.privateca.v1.PublicKey.KeyFormat;
34+
import com.google.cloud.security.privateca.v1.Subject;
35+
import com.google.cloud.security.privateca.v1.SubjectAltNames;
36+
import com.google.cloud.security.privateca.v1.X509Parameters;
37+
import com.google.cloud.security.privateca.v1.X509Parameters.CaOptions;
38+
import com.google.protobuf.ByteString;
39+
import com.google.protobuf.Duration;
40+
import java.io.IOException;
41+
import java.util.concurrent.ExecutionException;
42+
43+
public class CreateCertificate {
44+
45+
public static void main(String[] args)
46+
throws InterruptedException, ExecutionException, IOException {
47+
// TODO(developer): Replace these variables before running the sample.
48+
49+
// To sign and issue a certificate, a public key is essential. Here, we are making use
50+
// of Cloud KMS to retrieve an already created public key. Specify the following details to
51+
// retrieve the key. For more info, see: https://cloud.google.com/kms/docs/retrieve-public-key
52+
String project = "your-project-id";
53+
String kmsLocation = "kms-location";
54+
String keyRingId = "your-ring-id";
55+
String keyId = "your-key-id";
56+
String keyVersionId = "your-version-id";
57+
58+
// Retrieve the public key from Cloud KMS.
59+
ByteString publicKeyBytes =
60+
retrievePublicKey(project, kmsLocation, keyRingId, keyId, keyVersionId);
61+
62+
// location: For a list of locations, see:
63+
// https://cloud.google.com/certificate-authority-service/docs/locations
64+
// caPoolName: Set a unique name for the CA pool.
65+
// certificateAuthorityName: The name of the certificate authority which issues the certificate.
66+
// certificateName: Set a unique name for the certificate.
67+
String location = "ca-location";
68+
String caPoolName = "ca-pool-name";
69+
String certificateAuthorityName = "certificate-authority-name";
70+
String certificateName = "certificate-name";
71+
72+
createCertificate(
73+
project, location, caPoolName, certificateAuthorityName, certificateName, publicKeyBytes);
74+
}
75+
76+
// Create a Certificate which is issued by the Certificate Authority present in the CA Pool.
77+
// The key used to sign the certificate is created by the Cloud KMS.
78+
public static void createCertificate(
79+
String project,
80+
String location,
81+
String caPoolName,
82+
String certificateAuthorityName,
83+
String certificateName,
84+
ByteString publicKeyBytes)
85+
throws InterruptedException, ExecutionException, IOException {
86+
// Initialize client that will be used to send requests. This client only needs to be created
87+
// once, and can be reused for multiple requests. After completing all of your requests, call
88+
// the `certificateAuthorityServiceClient.close()` method on the client to safely
89+
// clean up any remaining background resources.
90+
try (CertificateAuthorityServiceClient certificateAuthorityServiceClient =
91+
CertificateAuthorityServiceClient.create()) {
92+
93+
// commonName: Enter a title for your certificate.
94+
// orgName: Provide the name of your company.
95+
// domainName: List the fully qualified domain name.
96+
// certificateLifetime: The validity of the certificate in seconds.
97+
String commonName = "common-name";
98+
String orgName = "org-name";
99+
String domainName = "dnsname.com";
100+
long certificateLifetime = 1000L;
101+
102+
// Set the Public Key and its format as obtained from the Cloud KMS.
103+
PublicKey publicKey =
104+
PublicKey.newBuilder().setKey(publicKeyBytes).setFormat(KeyFormat.PEM).build();
105+
106+
SubjectConfig subjectConfig =
107+
SubjectConfig.newBuilder()
108+
// Set the common name and org name.
109+
.setSubject(
110+
Subject.newBuilder().setCommonName(commonName).setOrganization(orgName).build())
111+
// Set the fully qualified domain name.
112+
.setSubjectAltName(SubjectAltNames.newBuilder().addDnsNames(domainName).build())
113+
.build();
114+
115+
// Set the X.509 fields required for the certificate.
116+
X509Parameters x509Parameters =
117+
X509Parameters.newBuilder()
118+
.setKeyUsage(
119+
KeyUsage.newBuilder()
120+
.setBaseKeyUsage(
121+
KeyUsageOptions.newBuilder()
122+
.setDigitalSignature(true)
123+
.setKeyEncipherment(true)
124+
.setCertSign(true)
125+
.build())
126+
.setExtendedKeyUsage(
127+
ExtendedKeyUsageOptions.newBuilder().setServerAuth(true).build())
128+
.build())
129+
.setCaOptions(CaOptions.newBuilder().setIsCa(true).buildPartial())
130+
.build();
131+
132+
// Create certificate.
133+
Certificate certificate =
134+
Certificate.newBuilder()
135+
.setConfig(
136+
CertificateConfig.newBuilder()
137+
.setPublicKey(publicKey)
138+
.setSubjectConfig(subjectConfig)
139+
.setX509Config(x509Parameters)
140+
.build())
141+
.setLifetime(Duration.newBuilder().setSeconds(certificateLifetime).build())
142+
.build();
143+
144+
// Create the Certificate Request.
145+
CreateCertificateRequest certificateRequest =
146+
CreateCertificateRequest.newBuilder()
147+
.setParent(CaPoolName.of(project, location, caPoolName).toString())
148+
.setCertificateId(certificateName)
149+
.setCertificate(certificate)
150+
.setIssuingCertificateAuthorityId(certificateAuthorityName)
151+
.build();
152+
153+
// Get the Certificate response.
154+
ApiFuture<Certificate> future =
155+
certificateAuthorityServiceClient
156+
.createCertificateCallable()
157+
.futureCall(certificateRequest);
158+
159+
Certificate response = future.get();
160+
// Get the PEM encoded, signed X.509 certificate.
161+
System.out.println(response.getPemCertificate());
162+
// To verify the obtained certificate, use this intermediate chain list.
163+
System.out.println(response.getPemCertificateChainList());
164+
}
165+
}
166+
167+
// Get the public Key used for signing the certificate from Cloud KMS.
168+
public static ByteString retrievePublicKey(
169+
String project, String kmsLocation, String keyRingId, String keyId, String keyVersionId)
170+
throws IOException {
171+
// Initialize client that will be used to send requests. This client only needs to be created
172+
// once, and can be reused for multiple requests. After completing all of your requests, call
173+
// the `client.close()` method on the client to safely
174+
// clean up any remaining background resources.
175+
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
176+
177+
CryptoKeyVersionName keyVersionName =
178+
CryptoKeyVersionName.of(project, kmsLocation, keyRingId, keyId, keyVersionId);
179+
com.google.cloud.kms.v1.PublicKey publicKey = client.getPublicKey(keyVersionName);
180+
181+
ByteString publicKeyBytes = publicKey.getPemBytes();
182+
return publicKeyBytes;
183+
}
184+
}
185+
}
186+
// [END privateca_create_certificate]

0 commit comments

Comments
 (0)