金融业一般会通过国密或者三方加密SDK实现。操作逻辑一致,可参考加密逻辑。以首选项存储用户的id为例,下面是一个参考国密 SM2 加密方式,结合首选项存储,对本地存储用户 ID 进行加密和解密的完整 DEMO。这个 DEMO 会生成 SM2 密钥对,使用公钥加密用户 ID 并存储到首选项中,之后使用私钥从首选项读取加密数据并解密:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
import { preferences } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; import { huks } from '@kit.UniversalKeystoreKit'; import { util } from '@kit.ArkTS'; import { common } from '@kit.AbilityKit'; // 首选项名称 const PRE_FS_NAME = 'user_id_storage'; // 加密算法枚举 enum EncryptionAlgorithm { SM2 = 'SM2', // 可根据需求添加更多算法 } /** * 加密工具类 */ class EncryptionUtils { private keyAlias: string; constructor(keyAlias: string) { this.keyAlias = keyAlias; } /** * 生成密钥 * @param algorithm 加密算法 */ async generateKey(algorithm: EncryptionAlgorithm) { let properties: Array<huks.HuksParam>; switch (algorithm) { case EncryptionAlgorithm.SM2: properties = [ { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 }, { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 }, { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT } ]; break; default: throw new Error(`Unsupported algorithm: ${algorithm}`); } const options: huks.HuksOptions = { properties }; await huks.generateKeyItem(this.keyAlias, options) .then((data) => { console.info(`Generate ${algorithm} key success, data = ${JSON.stringify(data)}`); }) .catch((error: Error) => { console.error(`Generate ${algorithm} key failed, ${JSON.stringify(error)}`); throw error; }); } /** * 加密数据 * @param data 待加密的数据 * @param algorithm 加密算法 * @returns 加密后的数据 */ async encrypt(data: string, algorithm: EncryptionAlgorithm): Promise<string> { let properties: Array<huks.HuksParam>; switch (algorithm) { case EncryptionAlgorithm.SM2: properties = [ { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 }, { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 }, { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT }, { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 } ]; break; default: throw new Error(`Unsupported algorithm: ${algorithm}`); } const options: huks.HuksOptions = { properties, inData: new Uint8Array(data.split('').map(c => c.charCodeAt(0))) }; let handleObj = await huks.initSession(this.keyAlias, options) const result = await huks.finishSession(handleObj.handle, options) .catch((error: Error) => { console.error(`Finish ${algorithm} encryption session failed: ${JSON.stringify(error)}`); throw error; }); let base64Helper = new util.Base64Helper(); let retStr = base64Helper.encodeToStringSync(result.outData as Uint8Array); return retStr; } /** * 解密数据 * @param encryptedData 加密后的数据 * @param algorithm 加密算法 * @returns 解密后的数据 */ async decrypt(encryptedData: string, algorithm: EncryptionAlgorithm): Promise<string> { let properties: Array<huks.HuksParam>; switch (algorithm) { case EncryptionAlgorithm.SM2: properties = [ { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 }, { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 }, { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }, { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 } ]; break; default: throw new Error(`Unsupported algorithm: ${algorithm}`); } let base64Helper = new util.Base64Helper(); let inData = base64Helper.decodeSync(encryptedData); const options: huks.HuksOptions = { properties, inData }; let handleObj = await huks.initSession(this.keyAlias, options) const result = await huks.finishSession(handleObj.handle, options) .catch((error: Error) => { console.error(`Finish ${algorithm} decryption session failed: ${JSON.stringify(error)}`); throw error; }); let retStr = base64Helper.encodeToStringSync(result.outData as Uint8Array); return retStr; } } /** * 首选项工具类 */ class PreferencesUtils { private preFs: preferences.Preferences | null = null; private context: common.UIAbilityContext; constructor(context: common.UIAbilityContext) { this.context = context; } /** * 初始化首选项实例 */ async init() { let options: preferences.Options = { name: PRE_FS_NAME }; this.preFs = preferences.getPreferencesSync(this.context, options); } /** * 存储数据 * @param key 键 * @param value 值 */ async put(key: string, value: string) { await this.preFs?.put(key, value) .then(() => console.info(`数据 ${key} 存储成功`)) .catch((err: BusinessError) => { console.error(`存储失败: ${err.code}, ${err.message}`); }); await this.preFs?.flush(); } /** * 读取数据 * @param key 键 * @returns 值或 null */ async get(key: string): Promise<preferences.ValueType> { let res = await this.preFs?.get(key, 'default') ?? ""; return res; } } |