• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
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 *     http://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
16import promptAction from '@ohos.promptAction';
17import Logger from '../util/Logger';
18import picker from '@ohos.file.picker';
19import { CryptoOperation } from '../cryptoframework/CryptoOperation';
20import TextFileManager from '../textfilemanager/TextFileManager';
21import common from '@ohos.app.ability.common';
22
23const TAG: string = '[Crypto_Framework]';
24
25@Component
26export struct Encrypt {
27  @State keyFileName: string = '';
28  @State keyFileUri: string = '';
29  @State textFileUri: string = '';
30  @State textFileName: string = '';
31  @State keyString: string = '';
32  @State cipherText: string = '';
33  @State plainText: string = '';
34  @State message: string = '';
35  @State createKeyUri: string = '';
36  @State encryptedFileUri: string = '';
37  private CryptoOperation: CryptoOperation = new CryptoOperation();
38
39  build() {
40    Stack({ alignContent: Alignment.Center }) {
41      Column() {
42        GridRow() {
43          GridCol({ span: { xs: 12, sm: 12, md: 12, lg: 12 } }) {
44            Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
45              List() {
46                ListItem() {
47                  Row() {
48                    Text($r('app.string.open_file'))
49                      .fontSize(16)
50                      .textAlign(TextAlign.Start)
51                      .lineHeight(22)
52
53                    Blank()
54
55                    Text(this.textFileName === '' ? $r('app.string.please_choose') : this.textFileName)
56                      .fontSize(14)
57                      .textAlign(TextAlign.Start)
58                      .lineHeight(19)
59
60                    Image($r('app.media.right_arrow'))
61                      .height('19vp')
62                      .width('10vp')
63                      .margin({ left: 9, right: 9, top: 6, bottom: 6 })
64                  }
65                  .backgroundColor(0xFFFFFF)
66                  .width('100%')
67                  .height('52vp')
68                  .padding({ top: 4, left: 12, right: 12 })
69                }.onClick(() => {
70                  this.selectTextFileAndRead();
71                })
72
73                ListItem() {
74                  Row() {
75                    Text($r('app.string.select_key_file'))
76                      .fontSize(16)
77                      .textAlign(TextAlign.Start)
78                      .lineHeight(22)
79
80                    Blank()
81
82                    Text(this.keyFileName === '' ? $r('app.string.please_choose') : this.keyFileName)
83                      .fontSize(14)
84                      .textAlign(TextAlign.Start)
85                      .lineHeight(19)
86
87                    Image($r('app.media.right_arrow'))
88                      .height('19vp')
89                      .width('10vp')
90                      .margin({ left: 9, right: 9, top: 6, bottom: 6 })
91                  }
92                  .backgroundColor(0xFFFFFF)
93                  .width('100%')
94                  .height('48vp')
95                  .padding({ left: 12, right: 12 })
96                }.onClick(() => {
97                  this.selectAesKeyFileAndRead();
98                })
99              }
100              .width('100%')
101              .height('100%')
102              .borderRadius(16)
103            }
104          }
105        }
106        .height('100vp')
107        .margin({ left: 12, right: 12, bottom: 12 })
108
109        GridRow() {
110          GridCol({ span: { xs: 12, sm: 12, md: 12, lg: 12 } }) {
111            Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
112              Column() {
113                Row() {
114                  Text($r('app.string.text_context'))
115                    .fontSize(16)
116                    .textAlign(TextAlign.Start)
117                    .fontWeight(500)
118                    .lineHeight(22)
119                }
120                .padding({ left: 12, right: 12 })
121                .width('100%')
122                .height('48vp')
123
124                Row() {
125                  Text() {
126                    Span(this.plainText)
127                      .fontSize(16)
128                      .fontWeight(400)
129                      .fontColor('#182431')
130                  }.textAlign(TextAlign.Start)
131                }
132                .padding({ left: 12, right: 12, bottom: 4 })
133                .width('100%')
134                .height('52vp')
135              }
136              .borderRadius(16)
137              .width('100%')
138              .height('100')
139              .backgroundColor(0xFFFFFF)
140            }
141          }
142        }
143        .height('100vp')
144        .margin({ left: 12, right: 12, bottom: 12 })
145
146        GridRow() {
147          GridCol({ span: { xs: 12, sm: 12, md: 12, lg: 12 } }) {
148            Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
149              Column() {
150                Row() {
151                  Text($r('app.string.encrypted_context'))
152                    .fontSize(16)
153                    .textAlign(TextAlign.Start)
154                    .fontWeight(500)
155                    .lineHeight(22)
156                }
157                .padding({ left: 12, right: 12 })
158                .width('100%')
159                .height('48vp')
160
161                Row() {
162                  Text() {
163                    Span(this.cipherText)
164                      .fontSize(16)
165                      .fontWeight(400)
166                      .fontColor('#182431')
167                  }.textAlign(TextAlign.Start)
168                }
169                .padding({ left: 12, right: 12, bottom: 4 })
170                .width('100%')
171                .height('52vp')
172              }
173              .borderRadius(16)
174              .width('100%')
175              .height('100')
176              .backgroundColor(0xFFFFFF)
177            }
178          }
179        }
180        .height('100vp')
181        .margin({ left: 12, right: 12, bottom: 12 })
182
183        Column() {
184          GridRow() {
185            GridCol({ span: { xs: 12, sm: 12, md: 12, lg: 12 } }) {
186              Column() {
187                Button() {
188                  Text($r('app.string.generate_aes_key_randomly')).fontSize(16).fontWeight(500)
189                    .lineHeight(22)
190                    .fontColor('#FFFFFF')
191                }
192                .id('encryptAesGenKey')
193                .borderRadius(20)
194                .type(ButtonType.Capsule)
195                .width('100%')
196                .height('40vp')
197                .margin({ bottom: 16 })
198                .backgroundColor('#007DFF')
199                .onClick(() => {
200                  this.genAesKey();
201                });
202
203                Button() {
204                  Text($r('app.string.encrypt')).fontSize(16).fontWeight(500)
205                    .lineHeight(22)
206                    .fontColor('#FFFFFF')
207                }
208                .borderRadius(20)
209                .id('encryptionBtn')
210                .type(ButtonType.Capsule)
211                .margin({ left: 24, right: 24 })
212                .width('100%')
213                .height('40vp')
214                .backgroundColor('#007DFF')
215                .onClick(() => {
216                  if (this.textFileUri === '' || this.keyFileUri === '') {
217                    promptAction.showToast({
218                      message: $r('app.string.null_message')
219                    });
220                  } else {
221                    this.encryptFunc();
222                  }
223                });
224              }
225            }
226          }.margin({ left: 24, right: 24 })
227        }.width('100%').height('296vp').justifyContent(FlexAlign.End)
228      }
229      .width('100%')
230      .height('100%')
231    }
232  }
233
234  async selectAesKeyFileAndRead() {
235    let config = {
236      action: 'ohos.want.action.OPEN_FILE',
237      parameters: {
238        startMode: 'choose',
239      }
240    }
241    let context = getContext(this) as common.UIAbilityContext;
242    let result = await context.startAbilityForResult(config);
243    if (result === null || result === undefined) {
244      Logger.error(TAG, `result is null or undefined!`);
245      return;
246    }
247    if (result.resultCode !== 0) {
248      Logger.error(TAG, `DocumentPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
249      return;
250    }
251    if (result.want.parameters.select_item_list === null || result.want.parameters.select_item_list === undefined) {
252      Logger.error(TAG, `result uri is null or undefined!`);
253      return;
254    }
255    if (result.want.parameters.file_name_list === null || result.want.parameters.file_name_list === undefined) {
256      Logger.error(TAG, `result file name is null or undefined!`);
257      return;
258    }
259    // 获取到密钥文档文件的URI
260    this.keyFileUri = result.want.parameters.select_item_list.toString();
261    // 获取到密钥文档文件的文件名称
262    this.keyFileName = result.want.parameters.file_name_list.toString();
263    await TextFileManager.readTextFile(this.keyFileUri);
264    this.keyString = TextFileManager.getString();
265  }
266
267  async selectTextFileAndRead() {
268    let config = {
269      action: 'ohos.want.action.OPEN_FILE',
270      parameters: {
271        startMode: 'choose',
272      }
273    }
274    let context = getContext(this) as common.UIAbilityContext;
275    let result = await context.startAbilityForResult(config);
276    if (result.resultCode !== 0) {
277      Logger.error(TAG, `DocumentPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
278      return;
279    }
280    if (result.want.parameters.select_item_list === null || result.want.parameters.select_item_list === undefined) {
281      Logger.error(TAG, `result uri is null or undefined!`);
282      return;
283    }
284    if (result.want.parameters.file_name_list === null || result.want.parameters.file_name_list === undefined) {
285      Logger.error(TAG, `result file name is null or undefined!`);
286      return;
287    }
288    // 获取到文档文件的URI
289    this.textFileUri = result.want.parameters.select_item_list.toString();
290    // 获取到文档文件的文件名称
291    this.textFileName = result.want.parameters.file_name_list.toString();
292    await TextFileManager.readTextFile(this.textFileUri);
293    this.plainText = TextFileManager.getString();
294  }
295
296  async createTextFileAndWrite() {
297    let documentSaveOptions = new picker.DocumentSaveOptions();
298    documentSaveOptions.newFileNames = ['cipherText.txt'];
299    let documentPicker = new picker.DocumentViewPicker();
300    let documentSaveResult = await documentPicker.save(documentSaveOptions);
301    this.encryptedFileUri = documentSaveResult[0];
302    await TextFileManager.writeTextFile(this.encryptedFileUri, this.cipherText);
303  }
304
305  async createKeyFileAndWrite() {
306    let documentSaveOptions = new picker.DocumentSaveOptions();
307    documentSaveOptions.newFileNames = ['aesKey.txt'];
308    let documentPicker = new picker.DocumentViewPicker();
309    let documentSaveResult = await documentPicker.save(documentSaveOptions);
310    this.createKeyUri = documentSaveResult[0];
311    await TextFileManager.writeTextFile(this.createKeyUri, this.keyString);
312  }
313
314  async encryptFunc() {
315    if (this.plainText === '' || this.keyFileUri === '') {
316      promptAction.showToast({
317        message: $r('app.string.null_message')
318      });
319      return;
320    }
321    try {
322      this.cipherText = await this.CryptoOperation.aesConvertAndEncrypt(this.keyString, this.plainText);
323    } catch (error) {
324      Logger.error(TAG, `encrypt failed, ${error.code}, ${error.message}`);
325      promptAction.showToast({
326        message: $r('app.string.encrypt_fail')
327      });
328    }
329    if (this.cipherText === '' || this.cipherText === undefined || this.cipherText === null) {
330      promptAction.showToast({
331        message: $r('app.string.encrypt_fail')
332      });
333      return;
334    } else {
335      try {
336        await this.createTextFileAndWrite();
337      } catch (error) {
338        Logger.error(TAG, `encrypt failed, ${error.code}, ${error.message}`);
339      }
340    }
341    if (this.encryptedFileUri === '' || typeof (this.encryptedFileUri) == 'undefined') {
342      promptAction.showToast({
343        message: $r('app.string.encrypt_fail')
344      });
345    } else {
346      promptAction.showToast({
347        message: $r('app.string.encrypt_success')
348      });
349    }
350  }
351
352  async genAesKey() {
353    try {
354      this.keyString = await this.CryptoOperation.generateAesKey();
355    } catch (error) {
356      Logger.error(TAG, `gen aes key failed, ${error.code}, ${error.message}`);
357    }
358    if (this.keyString === '' || typeof (this.keyString) == 'undefined') {
359      promptAction.showToast({
360        message: $r('app.string.gen_key_fail')
361      });
362      return;
363    } else {
364      try {
365        await this.createKeyFileAndWrite();
366      } catch (error) {
367        Logger.error(TAG, `write aes key failed, ${error.code}, ${error.message}`);
368      }
369    }
370    if (this.createKeyUri === '' || typeof (this.createKeyUri) == 'undefined') {
371      promptAction.showToast({
372        message: $r('app.string.gen_key_fail')
373      });
374    } else {
375      promptAction.showToast({
376        message: $r('app.string.gen_key_success')
377      });
378    }
379  }
380}
381
382