crypto.uts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. /**
  2. * AES 加密工具
  3. * 使用 AES-128-CBC 模式,PKCS7/PKCS5 填充
  4. */
  5. // 加密密钥和 IV(与后端保持一致)
  6. const KEY_STR = 'ygtxgxtkey030206'
  7. const IV_STR = 'ygtxgxt-iv030206'
  8. /**
  9. * AES 加密
  10. * @param word 需要加密的字符串
  11. * @returns 加密后的 Base64 字符串
  12. */
  13. export const encryptAES = (word: string): string => {
  14. // #ifdef APP-ANDROID
  15. return encryptAESAndroid(word, KEY_STR, IV_STR)
  16. // #endif
  17. // #ifdef APP-HARMONY
  18. return encryptAESHarmony(word, KEY_STR, IV_STR)
  19. // #endif
  20. // #ifdef APP-IOS
  21. return encryptAESiOS(word, KEY_STR, IV_STR)
  22. // #endif
  23. // #ifdef WEB
  24. return encryptAESWeb(word, KEY_STR, IV_STR)
  25. // #endif
  26. // #ifndef APP-ANDROID || APP-HARMONY || WEB
  27. // 其他平台暂时返回原文
  28. console.warn('当前平台暂不支持 AES 加密,返回原文')
  29. return word
  30. // #endif
  31. }
  32. /**
  33. * AES 解密
  34. * @param word 需要解密的 Base64 字符串
  35. * @returns 解密后的字符串
  36. */
  37. export const decryptAES = (word: string): string => {
  38. // #ifdef APP-ANDROID
  39. console.warn('APP-ANDROID')
  40. return decryptAESAndroid(word, KEY_STR, IV_STR)
  41. // #endif
  42. // #ifdef APP-HARMONY
  43. console.warn('APP-HARMONY')
  44. return decryptAESHarmony(word, KEY_STR, IV_STR)
  45. // #endif
  46. // #ifdef APP-IOS
  47. return decryptAESiOS(word, KEY_STR, IV_STR)
  48. // #endif
  49. // #ifdef WEB
  50. return decryptAESWeb(word, KEY_STR, IV_STR)
  51. // #endif
  52. // #ifndef APP-ANDROID || APP-HARMONY || WEB
  53. // 其他平台暂时返回原文
  54. console.warn('当前平台暂不支持 AES 解密,返回原文')
  55. return word
  56. // #endif
  57. }
  58. // Android 平台实现(使用条件编译)
  59. // #ifdef APP-ANDROID
  60. /**
  61. * Android 平台 AES 加密实现
  62. */
  63. function encryptAESAndroid(plainText: string, keyStr: string, ivStr: string): string {
  64. try {
  65. // 转换密钥和 IV 为字节数组
  66. const keyBytes = new java.lang.String(keyStr).getBytes("UTF-8")
  67. const ivBytes = new java.lang.String(ivStr).getBytes("UTF-8")
  68. // 创建密钥规范和 IV 规范
  69. const secretKeySpec = new javax.crypto.spec.SecretKeySpec(keyBytes, "AES")
  70. const ivParameterSpec = new javax.crypto.spec.IvParameterSpec(ivBytes)
  71. // 创建 Cipher 实例并初始化为加密模式
  72. // 注意:Java 中使用 PKCS5Padding,但在 AES 中它等同于 PKCS7Padding
  73. const cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding")
  74. cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)
  75. // 加密数据
  76. const plainBytes = new java.lang.String(plainText).getBytes("UTF-8")
  77. const encryptedBytes = cipher.doFinal(plainBytes)
  78. // 转为 Base64 字符串
  79. const base64Str = android.util.Base64.encodeToString(encryptedBytes, android.util.Base64.NO_WRAP)
  80. return base64Str.toString()
  81. } catch (e) {
  82. console.error('AES 加密失败', e)
  83. return plainText
  84. }
  85. }
  86. /**
  87. * Android 平台 AES 解密实现
  88. */
  89. function decryptAESAndroid(cipherText: string, keyStr: string, ivStr: string): string {
  90. try {
  91. // 转换密钥和 IV 为字节数组
  92. const keyBytes = new java.lang.String(keyStr).getBytes("UTF-8")
  93. const ivBytes = new java.lang.String(ivStr).getBytes("UTF-8")
  94. // 创建密钥规范和 IV 规范
  95. const secretKeySpec = new javax.crypto.spec.SecretKeySpec(keyBytes, "AES")
  96. const ivParameterSpec = new javax.crypto.spec.IvParameterSpec(ivBytes)
  97. // 创建 Cipher 实例并初始化为解密模式
  98. // 注意:Java 中使用 PKCS5Padding,但在 AES 中它等同于 PKCS7Padding
  99. const cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding")
  100. cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
  101. // 解密数据
  102. const cipherBytes = android.util.Base64.decode(cipherText, android.util.Base64.NO_WRAP)
  103. const decryptedBytes = cipher.doFinal(cipherBytes)
  104. // 转为字符串
  105. const decryptedStr = new java.lang.String(decryptedBytes, "UTF-8")
  106. return decryptedStr.toString()
  107. } catch (e) {
  108. console.error('AES 解密失败', e)
  109. return cipherText
  110. }
  111. }
  112. // #endif
  113. // ============ iOS 平台实现 ============
  114. // #ifdef APP-IOS
  115. /**
  116. * iOS 平台 AES 加密实现
  117. */
  118. function encryptAESiOS(plainText: string, keyStr: string, ivStr: string): string {
  119. try {
  120. // 使用 UTS 的 iOS 平台 API
  121. const plainData = plainText.dataUsingEncoding(4) // NSUTF8StringEncoding = 4
  122. const keyData = keyStr.dataUsingEncoding(4)
  123. const ivData = ivStr.dataUsingEncoding(4)
  124. if (!plainData || !keyData || !ivData) {
  125. console.error('AES 加密失败:数据转换错误')
  126. return plainText
  127. }
  128. // 准备加密参数
  129. const keyBytes = keyData.bytes
  130. const ivBytes = ivData.bytes
  131. const plainBytes = plainData.bytes
  132. const plainLength = plainData.length
  133. // 计算加密后数据大小
  134. const blockSize = 16 // AES 块大小
  135. const bufferSize = Math.floor((plainLength + blockSize) / blockSize) * blockSize
  136. // 创建输出缓冲区
  137. const buffer = plus.ios.newObject('NSMutableData', 'dataWithLength:', bufferSize)
  138. // 执行加密
  139. let encryptedLength = plus.ios.newObject('NSUInteger')
  140. const status = plus.ios.invoke('CCCrypt', ':',
  141. 0, // kCCEncrypt = 0
  142. 0, // kCCAlgorithmAES = 0
  143. 0x0001, // kCCOptionPKCS7Padding = 0x0001
  144. keyBytes,
  145. keyData.length,
  146. ivBytes,
  147. plainBytes,
  148. plainLength,
  149. buffer.bytes,
  150. bufferSize,
  151. plus.ios.addrOf(encryptedLength)
  152. )
  153. if (status !== 0) { // kCCSuccess = 0
  154. console.error('AES 加密失败,状态码:', status)
  155. return plainText
  156. }
  157. // 设置实际数据长度
  158. buffer.setLength(encryptedLength)
  159. // 转为 Base64 字符串
  160. const base64String = buffer.base64EncodedStringWithOptions(0)
  161. return String(base64String)
  162. } catch (e) {
  163. console.error('AES 加密失败(iOS)', e)
  164. return plainText
  165. }
  166. }
  167. /**
  168. * iOS 平台 AES 解密实现
  169. */
  170. function decryptAESiOS(cipherText: string, keyStr: string, ivStr: string): string {
  171. try {
  172. // Base64 字符串转为 Data
  173. const cipherData = plus.ios.invoke('NSData', 'alloc')
  174. const initData = plus.ios.invoke(cipherData, 'initWithBase64EncodedString:options:', cipherText, 0)
  175. if (!initData) {
  176. console.error('AES 解密失败:Base64 解码失败')
  177. return cipherText
  178. }
  179. const keyData = keyStr.dataUsingEncoding(4) // NSUTF8StringEncoding = 4
  180. const ivData = ivStr.dataUsingEncoding(4)
  181. if (!keyData || !ivData) {
  182. console.error('AES 解密失败:密钥或 IV 转换错误')
  183. return cipherText
  184. }
  185. // 准备解密参数
  186. const keyBytes = keyData.bytes
  187. const ivBytes = ivData.bytes
  188. const cipherBytes = cipherData.bytes
  189. const cipherLength = cipherData.length
  190. // 计算解密后数据大小(预留额外空间)
  191. const bufferSize = cipherLength + 16
  192. const buffer = plus.ios.newObject('NSMutableData', 'dataWithLength:', bufferSize)
  193. // 执行解密
  194. let decryptedLength = plus.ios.newObject('NSUInteger')
  195. const status = plus.ios.invoke('CCCrypt', ':',
  196. 1, // kCCDecrypt = 1
  197. 0, // kCCAlgorithmAES = 0
  198. 0x0001, // kCCOptionPKCS7Padding = 0x0001
  199. keyBytes,
  200. keyData.length,
  201. ivBytes,
  202. cipherBytes,
  203. cipherLength,
  204. buffer.bytes,
  205. bufferSize,
  206. plus.ios.addrOf(decryptedLength)
  207. )
  208. if (status !== 0) { // kCCSuccess = 0
  209. console.error('AES 解密失败,状态码:', status)
  210. return cipherText
  211. }
  212. // 设置实际数据长度
  213. buffer.setLength(decryptedLength)
  214. // 转为字符串
  215. const decryptedStr = plus.ios.invoke('NSString', 'alloc')
  216. const resultStr = plus.ios.invoke(decryptedStr, 'initWithData:encoding:', buffer, 4) // NSUTF8StringEncoding = 4
  217. return String(resultStr)
  218. } catch (e) {
  219. console.error('AES 解密失败(iOS)', e)
  220. return cipherText
  221. }
  222. }
  223. // 或者更简洁的 iOS 实现版本(使用 UTS 的 plus.ios API)
  224. function encryptAESiOS_simple(plainText: string, keyStr: string, ivStr: string): string {
  225. try {
  226. // 创建 CCCryptor
  227. const cryptorRef = plus.ios.newObject('CCCryptorRef')
  228. // 创建密钥和 IV 数据
  229. const keyData = plus.ios.invoke('NSData', 'dataWithBytes:length:',
  230. plus.ios.newObject('NSString', 'stringWithString:', keyStr).UTF8String,
  231. keyStr.length)
  232. const ivData = plus.ios.invoke('NSData', 'dataWithBytes:length:',
  233. plus.ios.newObject('NSString', 'stringWithString:', ivStr).UTF8String,
  234. ivStr.length)
  235. const plainData = plus.ios.invoke('NSData', 'dataWithBytes:length:',
  236. plus.ios.newObject('NSString', 'stringWithString:', plainText).UTF8String,
  237. plainText.length)
  238. // 创建输出缓冲区
  239. const bufferSize = plainData.length + 16
  240. const buffer = plus.ios.invoke('NSMutableData', 'dataWithLength:', bufferSize)
  241. // 执行加密
  242. let dataOutMoved = 0
  243. const status = plus.ios.invoke('CCCrypt',
  244. 0, // kCCEncrypt
  245. 0, // kCCAlgorithmAES128
  246. 1, // kCCOptionPKCS7Padding
  247. keyData.bytes,
  248. keyData.length,
  249. ivData.bytes,
  250. plainData.bytes,
  251. plainData.length,
  252. buffer.bytes,
  253. buffer.length,
  254. dataOutMoved
  255. )
  256. if (status === 0) { // kCCSuccess
  257. buffer.setLength(dataOutMoved)
  258. const base64Str = buffer.base64EncodedStringWithOptions(0)
  259. return String(base64Str)
  260. } else {
  261. console.error('加密失败,错误码:', status)
  262. return plainText
  263. }
  264. } catch (e) {
  265. console.error('AES 加密失败(iOS)', e)
  266. return plainText
  267. }
  268. }
  269. function decryptAESiOS_simple(cipherText: string, keyStr: string, ivStr: string): string {
  270. try {
  271. // Base64 解码
  272. const cipherData = plus.ios.invoke('NSData', 'alloc')
  273. const initData = plus.ios.invoke(cipherData, 'initWithBase64EncodedString:options:', cipherText, 0)
  274. if (!initData) {
  275. console.error('解密失败:Base64 解码失败')
  276. return cipherText
  277. }
  278. // 创建密钥和 IV 数据
  279. const keyData = plus.ios.invoke('NSData', 'dataWithBytes:length:',
  280. plus.ios.newObject('NSString', 'stringWithString:', keyStr).UTF8String,
  281. keyStr.length)
  282. const ivData = plus.ios.invoke('NSData', 'dataWithBytes:length:',
  283. plus.ios.newObject('NSString', 'stringWithString:', ivStr).UTF8String,
  284. ivStr.length)
  285. // 创建输出缓冲区
  286. const buffer = plus.ios.invoke('NSMutableData', 'dataWithLength:', cipherData.length)
  287. // 执行解密
  288. let dataOutMoved = 0
  289. const status = plus.ios.invoke('CCCrypt',
  290. 1, // kCCDecrypt
  291. 0, // kCCAlgorithmAES128
  292. 1, // kCCOptionPKCS7Padding
  293. keyData.bytes,
  294. keyData.length,
  295. ivData.bytes,
  296. cipherData.bytes,
  297. cipherData.length,
  298. buffer.bytes,
  299. buffer.length,
  300. dataOutMoved
  301. )
  302. if (status === 0) { // kCCSuccess
  303. buffer.setLength(dataOutMoved)
  304. const resultStr = plus.ios.invoke('NSString', 'alloc')
  305. const finalStr = plus.ios.invoke(resultStr, 'initWithData:encoding:', buffer, 4) // NSUTF8StringEncoding = 4
  306. return String(finalStr)
  307. } else {
  308. console.error('解密失败,错误码:', status)
  309. return cipherText
  310. }
  311. } catch (e) {
  312. console.error('AES 解密失败(iOS)', e)
  313. return cipherText
  314. }
  315. }
  316. // #endif
  317. // 鸿蒙平台 AES 加密实现
  318. // #ifdef APP-HARMONY
  319. /**
  320. * 鸿蒙平台 AES 加密实现
  321. * 使用纯 TypeScript 实现 AES-128-CBC
  322. */
  323. function encryptAESHarmony(plainText: string, keyStr: string, ivStr: string): string {
  324. try {
  325. return encryptAESPure(plainText, keyStr, ivStr)
  326. } catch (e) {
  327. console.error('AES 加密失败(鸿蒙)', e)
  328. return plainText
  329. }
  330. }
  331. /**
  332. * 鸿蒙平台 AES 解密实现
  333. */
  334. function decryptAESHarmony(cipherText: string, keyStr: string, ivStr: string): string {
  335. try {
  336. return decryptAESPure(cipherText, keyStr, ivStr)
  337. } catch (e) {
  338. console.error('AES 解密失败(鸿蒙)', e)
  339. return cipherText
  340. }
  341. }
  342. // #endif
  343. // Web 平台 AES 加密实现
  344. // #ifdef WEB
  345. /**
  346. * Web 平台 AES 加密实现
  347. * 使用纯 TypeScript 实现 AES-128-CBC
  348. */
  349. function encryptAESWeb(plainText: string, keyStr: string, ivStr: string): string {
  350. try {
  351. return encryptAESPure(plainText, keyStr, ivStr)
  352. } catch (e) {
  353. console.error('加密失败(Web)', e)
  354. return plainText
  355. }
  356. }
  357. /**
  358. * Web 平台 AES 解密实现
  359. */
  360. function decryptAESWeb(cipherText: string, keyStr: string, ivStr: string): string {
  361. try {
  362. return decryptAESPure(cipherText, keyStr, ivStr)
  363. } catch (e) {
  364. console.error('解密失败(Web)', e)
  365. return cipherText
  366. }
  367. }
  368. // #endif
  369. // 纯 TypeScript 实现的 AES 加密(用于 Web 和鸿蒙平台)
  370. // #ifndef APP-ANDROID
  371. /**
  372. * 纯 TypeScript AES 加密实现(简化版 CryptoJS 逻辑)
  373. */
  374. function encryptAESPure(plainText: string, keyStr: string, ivStr: string): string {
  375. // 将字符串转为字节数组
  376. const plainBytes = stringToBytes(plainText)
  377. const keyBytes = stringToBytes(keyStr)
  378. const ivBytes = stringToBytes(ivStr)
  379. // PKCS7 填充
  380. const paddedBytes = pkcs7Pad(plainBytes)
  381. // AES-CBC 加密
  382. const encryptedBytes = aesCBCEncrypt(paddedBytes, keyBytes, ivBytes)
  383. // 转为 Base64
  384. return bytesToBase64(encryptedBytes)
  385. }
  386. /**
  387. * 纯 TypeScript AES 解密实现
  388. */
  389. function decryptAESPure(cipherText: string, keyStr: string, ivStr: string): string {
  390. // Base64 转字节数组
  391. const cipherBytes = base64ToBytes(cipherText)
  392. const keyBytes = stringToBytes(keyStr)
  393. const ivBytes = stringToBytes(ivStr)
  394. // AES-CBC 解密
  395. const decryptedBytes = aesCBCDecrypt(cipherBytes, keyBytes, ivBytes)
  396. // 去除 PKCS7 填充
  397. const unpaddedBytes = pkcs7Unpad(decryptedBytes)
  398. // 转为字符串
  399. return bytesToString(unpaddedBytes)
  400. }
  401. // ============ 辅助函数 ============
  402. /**
  403. * 字符串转字节数组(UTF-8)
  404. */
  405. function stringToBytes(str: string): number[] {
  406. const bytes: number[] = []
  407. for (let i = 0; i < str.length; i++) {
  408. const charCode = str.charCodeAt(i)
  409. if (charCode < 0x80) {
  410. bytes.push(charCode)
  411. } else if (charCode < 0x800) {
  412. bytes.push(0xc0 | (charCode >> 6))
  413. bytes.push(0x80 | (charCode & 0x3f))
  414. } else if (charCode < 0xd800 || charCode >= 0xe000) {
  415. bytes.push(0xe0 | (charCode >> 12))
  416. bytes.push(0x80 | ((charCode >> 6) & 0x3f))
  417. bytes.push(0x80 | (charCode & 0x3f))
  418. } else {
  419. // UTF-16 代理对
  420. i++
  421. const surrogate = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff))
  422. bytes.push(0xf0 | (surrogate >> 18))
  423. bytes.push(0x80 | ((surrogate >> 12) & 0x3f))
  424. bytes.push(0x80 | ((surrogate >> 6) & 0x3f))
  425. bytes.push(0x80 | (surrogate & 0x3f))
  426. }
  427. }
  428. return bytes
  429. }
  430. /**
  431. * 字节数组转字符串(UTF-8)
  432. */
  433. function bytesToString(bytes: number[]): string {
  434. let str = ''
  435. let i = 0
  436. while (i < bytes.length) {
  437. const byte = bytes[i]
  438. if (byte < 0x80) {
  439. str += String.fromCharCode(byte)
  440. i++
  441. } else if (byte < 0xe0) {
  442. str += String.fromCharCode(((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f))
  443. i += 2
  444. } else if (byte < 0xf0) {
  445. str += String.fromCharCode(((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f))
  446. i += 3
  447. } else {
  448. const codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f)
  449. const surrogate = codePoint - 0x10000
  450. str += String.fromCharCode(0xd800 + (surrogate >> 10), 0xdc00 + (surrogate & 0x3ff))
  451. i += 4
  452. }
  453. }
  454. return str
  455. }
  456. /**
  457. * 字节数组转 Base64
  458. */
  459. function bytesToBase64(bytes: number[]): string {
  460. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  461. let base64 = ''
  462. for (let i = 0; i < bytes.length; i += 3) {
  463. const byte1 = bytes[i]
  464. const byte2 = i + 1 < bytes.length ? bytes[i + 1] : 0
  465. const byte3 = i + 2 < bytes.length ? bytes[i + 2] : 0
  466. const enc1 = byte1 >> 2
  467. const enc2 = ((byte1 & 3) << 4) | (byte2 >> 4)
  468. const enc3 = ((byte2 & 15) << 2) | (byte3 >> 6)
  469. const enc4 = byte3 & 63
  470. base64 += chars.charAt(enc1) + chars.charAt(enc2)
  471. base64 += i + 1 < bytes.length ? chars.charAt(enc3) : '='
  472. base64 += i + 2 < bytes.length ? chars.charAt(enc4) : '='
  473. }
  474. return base64
  475. }
  476. /**
  477. * Base64 转字节数组
  478. */
  479. function base64ToBytes(base64: string): number[] {
  480. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  481. const bytes: number[] = []
  482. for (let i = 0; i < base64.length; i += 4) {
  483. const enc1 = chars.indexOf(base64.charAt(i))
  484. const enc2 = chars.indexOf(base64.charAt(i + 1))
  485. const enc3 = chars.indexOf(base64.charAt(i + 2))
  486. const enc4 = chars.indexOf(base64.charAt(i + 3))
  487. const byte1 = (enc1 << 2) | (enc2 >> 4)
  488. const byte2 = ((enc2 & 15) << 4) | (enc3 >> 2)
  489. const byte3 = ((enc3 & 3) << 6) | enc4
  490. bytes.push(byte1)
  491. if (enc3 !== -1) bytes.push(byte2)
  492. if (enc4 !== -1) bytes.push(byte3)
  493. }
  494. return bytes
  495. }
  496. /**
  497. * PKCS7 填充
  498. */
  499. function pkcs7Pad(bytes: number[]): number[] {
  500. const blockSize = 16
  501. const padding = blockSize - (bytes.length % blockSize)
  502. const paddedBytes = bytes.slice()
  503. for (let i = 0; i < padding; i++) {
  504. paddedBytes.push(padding)
  505. }
  506. return paddedBytes
  507. }
  508. /**
  509. * PKCS7 去填充
  510. */
  511. function pkcs7Unpad(bytes: number[]): number[] {
  512. const padding = bytes[bytes.length - 1]
  513. return bytes.slice(0, bytes.length - padding)
  514. }
  515. /**
  516. * AES-CBC 加密
  517. */
  518. function aesCBCEncrypt(plainBytes: number[], keyBytes: number[], ivBytes: number[]): number[] {
  519. const blocks = []
  520. const blockSize = 16
  521. let previousBlock = ivBytes.slice()
  522. // 扩展密钥
  523. const expandedKey = expandKey(keyBytes)
  524. // 分块加密
  525. for (let i = 0; i < plainBytes.length; i += blockSize) {
  526. const block = plainBytes.slice(i, i + blockSize)
  527. // CBC 模式:先与上一个密文块异或
  528. const xorBlock = xorBytes(block, previousBlock)
  529. // AES 加密
  530. const encryptedBlock = aesEncryptBlock(xorBlock, expandedKey)
  531. blocks.push(...encryptedBlock)
  532. previousBlock = encryptedBlock
  533. }
  534. return blocks
  535. }
  536. /**
  537. * AES-CBC 解密
  538. */
  539. function aesCBCDecrypt(cipherBytes: number[], keyBytes: number[], ivBytes: number[]): number[] {
  540. const blocks = []
  541. const blockSize = 16
  542. let previousBlock = ivBytes.slice()
  543. // 扩展密钥
  544. const expandedKey = expandKey(keyBytes)
  545. // 分块解密
  546. for (let i = 0; i < cipherBytes.length; i += blockSize) {
  547. const block = cipherBytes.slice(i, i + blockSize)
  548. // AES 解密
  549. const decryptedBlock = aesDecryptBlock(block, expandedKey)
  550. // CBC 模式:再与上一个密文块异或
  551. const xorBlock = xorBytes(decryptedBlock, previousBlock)
  552. blocks.push(...xorBlock)
  553. previousBlock = block
  554. }
  555. return blocks
  556. }
  557. /**
  558. * 字节数组异或
  559. */
  560. function xorBytes(a: number[], b: number[]): number[] {
  561. const result: number[] = []
  562. for (let i = 0; i < a.length; i++) {
  563. result.push(a[i] ^ b[i])
  564. }
  565. return result
  566. }
  567. /**
  568. * AES 密钥扩展
  569. */
  570. function expandKey(key: number[]): number[][] {
  571. const Nk = 4 // 128-bit key
  572. const Nr = 10 // 10 rounds
  573. const w: number[][] = []
  574. // 初始化前 Nk 个字
  575. for (let i = 0; i < Nk; i++) {
  576. w[i] = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]
  577. }
  578. // 扩展密钥
  579. for (let i = Nk; i < 4 * (Nr + 1); i++) {
  580. let temp = w[i - 1].slice()
  581. if (i % Nk === 0) {
  582. temp = xorWord(subWord(rotWord(temp)), rcon(i / Nk))
  583. }
  584. w[i] = xorWord(w[i - Nk], temp)
  585. }
  586. return w
  587. }
  588. /**
  589. * AES 加密单个块
  590. */
  591. function aesEncryptBlock(block: number[], expandedKey: number[][]): number[] {
  592. const state = blockToState(block)
  593. const Nr = 10
  594. addRoundKey(state, expandedKey, 0)
  595. for (let round = 1; round < Nr; round++) {
  596. subBytes(state)
  597. shiftRows(state)
  598. mixColumns(state)
  599. addRoundKey(state, expandedKey, round)
  600. }
  601. subBytes(state)
  602. shiftRows(state)
  603. addRoundKey(state, expandedKey, Nr)
  604. return stateToBlock(state)
  605. }
  606. /**
  607. * AES 解密单个块
  608. */
  609. function aesDecryptBlock(block: number[], expandedKey: number[][]): number[] {
  610. const state = blockToState(block)
  611. const Nr = 10
  612. addRoundKey(state, expandedKey, Nr)
  613. for (let round = Nr - 1; round > 0; round--) {
  614. invShiftRows(state)
  615. invSubBytes(state)
  616. addRoundKey(state, expandedKey, round)
  617. invMixColumns(state)
  618. }
  619. invShiftRows(state)
  620. invSubBytes(state)
  621. addRoundKey(state, expandedKey, 0)
  622. return stateToBlock(state)
  623. }
  624. // ============ AES 核心函数 ============
  625. // S-box
  626. const sbox = [
  627. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
  628. 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
  629. 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  630. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
  631. 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
  632. 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  633. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
  634. 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
  635. 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  636. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
  637. 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  638. 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  639. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
  640. 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
  641. 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  642. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
  643. ]
  644. // 逆 S-box
  645. const invSbox = [
  646. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
  647. 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
  648. 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  649. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
  650. 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
  651. 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  652. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
  653. 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
  654. 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  655. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
  656. 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
  657. 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  658. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
  659. 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
  660. 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  661. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
  662. ]
  663. // Rcon
  664. const rcon_array = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
  665. function rcon(i: number): number[] {
  666. return [rcon_array[i], 0, 0, 0]
  667. }
  668. function rotWord(word: number[]): number[] {
  669. return [word[1], word[2], word[3], word[0]]
  670. }
  671. function subWord(word: number[]): number[] {
  672. return word.map(b => sbox[b])
  673. }
  674. function xorWord(a: number[], b: number[]): number[] {
  675. return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]
  676. }
  677. function blockToState(block: number[]): number[][] {
  678. const state: number[][] = []
  679. for (let i = 0; i < 4; i++) {
  680. state[i] = []
  681. for (let j = 0; j < 4; j++) {
  682. state[i][j] = block[i + 4 * j]
  683. }
  684. }
  685. return state
  686. }
  687. function stateToBlock(state: number[][]): number[] {
  688. const block: number[] = []
  689. for (let j = 0; j < 4; j++) {
  690. for (let i = 0; i < 4; i++) {
  691. block.push(state[i][j])
  692. }
  693. }
  694. return block
  695. }
  696. function addRoundKey(state: number[][], expandedKey: number[][], round: number): void {
  697. for (let i = 0; i < 4; i++) {
  698. for (let j = 0; j < 4; j++) {
  699. state[i][j] ^= expandedKey[round * 4 + j][i]
  700. }
  701. }
  702. }
  703. function subBytes(state: number[][]): void {
  704. for (let i = 0; i < 4; i++) {
  705. for (let j = 0; j < 4; j++) {
  706. state[i][j] = sbox[state[i][j]]
  707. }
  708. }
  709. }
  710. function invSubBytes(state: number[][]): void {
  711. for (let i = 0; i < 4; i++) {
  712. for (let j = 0; j < 4; j++) {
  713. state[i][j] = invSbox[state[i][j]]
  714. }
  715. }
  716. }
  717. function shiftRows(state: number[][]): void {
  718. let temp: number
  719. // Row 1: shift left by 1
  720. temp = state[1][0]
  721. state[1][0] = state[1][1]
  722. state[1][1] = state[1][2]
  723. state[1][2] = state[1][3]
  724. state[1][3] = temp
  725. // Row 2: shift left by 2
  726. temp = state[2][0]
  727. state[2][0] = state[2][2]
  728. state[2][2] = temp
  729. temp = state[2][1]
  730. state[2][1] = state[2][3]
  731. state[2][3] = temp
  732. // Row 3: shift left by 3 (or right by 1)
  733. temp = state[3][3]
  734. state[3][3] = state[3][2]
  735. state[3][2] = state[3][1]
  736. state[3][1] = state[3][0]
  737. state[3][0] = temp
  738. }
  739. function invShiftRows(state: number[][]): void {
  740. let temp: number
  741. // Row 1: shift right by 1
  742. temp = state[1][3]
  743. state[1][3] = state[1][2]
  744. state[1][2] = state[1][1]
  745. state[1][1] = state[1][0]
  746. state[1][0] = temp
  747. // Row 2: shift right by 2
  748. temp = state[2][0]
  749. state[2][0] = state[2][2]
  750. state[2][2] = temp
  751. temp = state[2][1]
  752. state[2][1] = state[2][3]
  753. state[2][3] = temp
  754. // Row 3: shift right by 3 (or left by 1)
  755. temp = state[3][0]
  756. state[3][0] = state[3][1]
  757. state[3][1] = state[3][2]
  758. state[3][2] = state[3][3]
  759. state[3][3] = temp
  760. }
  761. function mixColumns(state: number[][]): void {
  762. for (let j = 0; j < 4; j++) {
  763. const s0 = state[0][j]
  764. const s1 = state[1][j]
  765. const s2 = state[2][j]
  766. const s3 = state[3][j]
  767. state[0][j] = gfMul(0x02, s0) ^ gfMul(0x03, s1) ^ s2 ^ s3
  768. state[1][j] = s0 ^ gfMul(0x02, s1) ^ gfMul(0x03, s2) ^ s3
  769. state[2][j] = s0 ^ s1 ^ gfMul(0x02, s2) ^ gfMul(0x03, s3)
  770. state[3][j] = gfMul(0x03, s0) ^ s1 ^ s2 ^ gfMul(0x02, s3)
  771. }
  772. }
  773. function invMixColumns(state: number[][]): void {
  774. for (let j = 0; j < 4; j++) {
  775. const s0 = state[0][j]
  776. const s1 = state[1][j]
  777. const s2 = state[2][j]
  778. const s3 = state[3][j]
  779. state[0][j] = gfMul(0x0e, s0) ^ gfMul(0x0b, s1) ^ gfMul(0x0d, s2) ^ gfMul(0x09, s3)
  780. state[1][j] = gfMul(0x09, s0) ^ gfMul(0x0e, s1) ^ gfMul(0x0b, s2) ^ gfMul(0x0d, s3)
  781. state[2][j] = gfMul(0x0d, s0) ^ gfMul(0x09, s1) ^ gfMul(0x0e, s2) ^ gfMul(0x0b, s3)
  782. state[3][j] = gfMul(0x0b, s0) ^ gfMul(0x0d, s1) ^ gfMul(0x09, s2) ^ gfMul(0x0e, s3)
  783. }
  784. }
  785. /**
  786. * 伽罗瓦域乘法
  787. */
  788. function gfMul(a: number, b: number): number {
  789. let p = 0
  790. for (let i = 0; i < 8; i++) {
  791. if ((b & 1) !== 0) {
  792. p ^= a
  793. }
  794. const hiBitSet = (a & 0x80) !== 0
  795. a = (a << 1) & 0xff
  796. if (hiBitSet) {
  797. a ^= 0x1b // AES 的不可约多项式
  798. }
  799. b >>= 1
  800. }
  801. return p
  802. }
  803. // #endif