1+ // Copyright 2022 Google LLC
2+ //
3+ // Licensed under the Apache License, Version 2.0 (the "License");
4+ // you may not use this file except in compliance with the License.
5+ // You may obtain a copy of the License at
6+ //
7+ // https://www.apache.org/licenses/LICENSE-2.0
8+ //
9+ // Unless required by applicable law or agreed to in writing, software
10+ // distributed under the License is distributed on an "AS IS" BASIS,
11+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+ // See the License for the specific language governing permissions and
13+ // limitations under the License.
14+
15+
16+ // [START gmail_create_smime_info]
17+ import com .google .api .services .gmail .model .SmimeInfo ;
18+ import java .io .File ;
19+ import java .io .FileInputStream ;
20+ import java .io .IOException ;
21+ import java .io .InputStream ;
22+ import java .util .Base64 ;
23+
24+ /* Class to demonstrate the use of Gmail Create SmimeInfo API */
25+ public class CreateSmimeInfo {
26+ /**
27+ * Create an SmimeInfo resource for a certificate from file.
28+ *
29+ * @param filename Name of the file containing the S/MIME certificate.
30+ * @param password Password for the certificate file, or null if the file is not
31+ * password-protected.
32+ * @return An SmimeInfo object with the specified certificate.
33+ */
34+ public static SmimeInfo createSmimeInfo (String filename , String password ) {
35+ SmimeInfo smimeInfo = null ;
36+ InputStream in = null ;
37+
38+ try {
39+ File file = new File (filename );
40+ in = new FileInputStream (file );
41+ byte [] fileContent = new byte [(int ) file .length ()];
42+ in .read (fileContent );
43+
44+ smimeInfo = new SmimeInfo ();
45+ smimeInfo .setPkcs12 (Base64 .getUrlEncoder ().encodeToString (fileContent ));
46+ if (password != null && password .length () > 0 ) {
47+ smimeInfo .setEncryptedKeyPassword (password );
48+ }
49+ } catch (Exception e ) {
50+ System .out .printf ("An error occured while reading the certificate file: %s\n " , e );
51+ } finally {
52+ try {
53+ if (in != null ) {
54+ in .close ();
55+ }
56+ } catch (IOException ioe ) {
57+ System .out .printf ("An error occured while closing the input stream: %s\n " , ioe );
58+ }
59+ }
60+ return smimeInfo ;
61+ }
62+ }
63+ // [END gmail_create_smime_info]
0 commit comments