1/* 2 * Copyright (c) 2025 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 16// [Start sync_symmetry_encrypt_decrypt_sm4] 17import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 18import { buffer } from '@kit.ArkTS'; 19 20// 加密消息 21function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) { 22 let cipher = cryptoFramework.createCipher('SM4_128|ECB|PKCS7'); 23 cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null); 24 let encryptData = cipher.doFinalSync(plainText); 25 return encryptData; 26} 27 28// 解密消息 29function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) { 30 let decoder = cryptoFramework.createCipher('SM4_128|ECB|PKCS7'); 31 decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null); 32 let decryptData = decoder.doFinalSync(cipherText); 33 return decryptData; 34} 35 36function genSymKeyByData(symKeyData: Uint8Array) { 37 let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData }; 38 let symGenerator = cryptoFramework.createSymKeyGenerator('SM4_128'); 39 let symKey = symGenerator.convertKeySync(symKeyBlob); 40 console.info('convertKeySync success'); 41 return symKey; 42} 43 44function main() { 45 let keyData = new Uint8Array([7, 154, 52, 176, 4, 236, 150, 43, 237, 9, 145, 166, 141, 174, 224, 131]); 46 let symKey = genSymKeyByData(keyData); 47 let message = 'This is a test'; 48 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 49 let encryptText = encryptMessage(symKey, plainText); 50 let decryptText = decryptMessage(symKey, encryptText); 51 if (plainText.data.toString() === decryptText.data.toString()) { 52 console.info('decrypt ok'); 53 console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8')); 54 } else { 55 console.error('decrypt failed'); 56 } 57} 58// [End sync_symmetry_encrypt_decrypt_sm4] 59 60@Entry 61@Component 62struct Index { 63 @State message: string = 'Encryption Decryption Guidance SM4 ArkTs'; 64 65 build() { 66 Column({ space: 12 }) { 67 Text(this.message).fontSize(20).fontWeight(FontWeight.Bold) 68 Button($r('app.string.call_sm4_ecb_synchronous')) 69 .width('70%') 70 .onClick(() => { 71 try { 72 main(); 73 this.message = 'SM4_ECBSuccess'; 74 } catch { 75 this.message = 'SM4_ECBFail'; 76 } 77 }) 78 } 79 .height('100%') 80 .width('100%') 81 } 82}