crc-tool.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. const {
  2. CRC_ALGORITHM_PRESETS,
  3. calculateCrc
  4. } = require('../../utils/crc.js')
  5. const {
  6. HASH_ALGORITHM_PRESETS,
  7. calculateHash
  8. } = require('./hash.js')
  9. const {
  10. formatBytes,
  11. stringToUtf8Bytes
  12. } = require('../../utils/binary-utils.js')
  13. const INPUT_TYPE_OPTIONS = [
  14. { key: 'hex', label: 'HEX' },
  15. { key: 'string', label: 'String' },
  16. { key: 'base64', label: 'Base64' }
  17. ]
  18. const ALGORITHM_PRESETS = CRC_ALGORITHM_PRESETS
  19. .map((preset) => ({ ...preset, kind: 'crc' }))
  20. .concat(HASH_ALGORITHM_PRESETS)
  21. const CRC_CONFIG_FIELDS = [
  22. 'crcInitialValue',
  23. 'crcPoly',
  24. 'crcWidth',
  25. 'crcXorOut'
  26. ]
  27. function clonePreset(preset) {
  28. return {
  29. ...preset
  30. }
  31. }
  32. function getPreset(index) {
  33. return clonePreset(ALGORITHM_PRESETS[Number(index)] || ALGORITHM_PRESETS[0])
  34. }
  35. function getCustomPresetIndex() {
  36. return Math.max(0, ALGORITHM_PRESETS.findIndex((preset) => preset.custom))
  37. }
  38. function getInputType(index) {
  39. return INPUT_TYPE_OPTIONS[Number(index)] || INPUT_TYPE_OPTIONS[0]
  40. }
  41. function createPresetState(presetIndex = 0) {
  42. const preset = getPreset(presetIndex)
  43. const kind = preset.kind || 'crc'
  44. return {
  45. crcAlgorithmCollapsed: !(preset.custom || kind === 'hmac' || kind === 'pbkdf2'),
  46. crcAlgorithmKind: kind,
  47. crcInitialValue: preset.init || 'FFFF',
  48. crcPoly: preset.poly || '1021',
  49. crcPresetIndex: Number(presetIndex),
  50. crcReflectIn: !!preset.reflectIn,
  51. crcReflectOut: !!preset.reflectOut,
  52. crcShowBinResult: kind === 'crc',
  53. crcShowCrcConfig: kind === 'crc',
  54. crcShowHmacKey: kind === 'hmac',
  55. crcShowPbkdf2Config: kind === 'pbkdf2',
  56. crcWidth: String(preset.width || 16),
  57. crcXorOut: preset.xorOut || '0000'
  58. }
  59. }
  60. function createInitialState() {
  61. return {
  62. ...createPresetState(0),
  63. crcDataLengthText: '0 bytes',
  64. crcDataText: '',
  65. crcErrorText: '',
  66. crcFileName: '',
  67. crcFileSizeText: '',
  68. crcHmacKey: '',
  69. crcInputTypeIndex: 0,
  70. crcInputTypeOptions: INPUT_TYPE_OPTIONS,
  71. crcPbkdf2Iterations: '1000',
  72. crcPbkdf2Length: '32',
  73. crcPbkdf2Salt: '',
  74. crcPresetOptions: ALGORITHM_PRESETS.map(clonePreset),
  75. crcResultBase64: '--',
  76. crcResultBin: '--',
  77. crcResultBinLines: splitBinaryResult('--'),
  78. crcResultHex: '--'
  79. }
  80. }
  81. function normalizeHexData(text) {
  82. return String(text || '')
  83. .replace(/0x/gi, '')
  84. .replace(/[\s,_:-]/g, '')
  85. }
  86. function parseHexBytes(text) {
  87. const hexText = normalizeHexData(text)
  88. if (!hexText) return []
  89. if (!/^[0-9A-F]+$/i.test(hexText)) throw new Error('HEX 数据包含非法字符')
  90. if (hexText.length % 2 !== 0) throw new Error('HEX 数据长度必须为偶数字符')
  91. const bytes = []
  92. for (let index = 0; index < hexText.length; index += 2) {
  93. bytes.push(parseInt(hexText.slice(index, index + 2), 16))
  94. }
  95. return bytes
  96. }
  97. function parseBase64Bytes(text) {
  98. const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  99. let normalized = String(text || '').replace(/\s/g, '')
  100. if (!normalized) return []
  101. if (normalized.length % 4 === 1 || /[^A-Za-z0-9+/=]/.test(normalized)) {
  102. throw new Error('Base64 数据无效')
  103. }
  104. while (normalized.length % 4 !== 0) {
  105. normalized += '='
  106. }
  107. const bytes = []
  108. for (let index = 0; index < normalized.length; index += 4) {
  109. const chars = normalized.slice(index, index + 4)
  110. const values = chars.split('').map((char) => (char === '=' ? 0 : alphabet.indexOf(char)))
  111. if (values.some((value) => value < 0)) throw new Error('Base64 数据无效')
  112. const triple = (values[0] << 18) | (values[1] << 12) | (values[2] << 6) | values[3]
  113. bytes.push((triple >> 16) & 0xFF)
  114. if (chars[2] !== '=') bytes.push((triple >> 8) & 0xFF)
  115. if (chars[3] !== '=') bytes.push(triple & 0xFF)
  116. }
  117. return bytes
  118. }
  119. function parseInputBytes(dataText, inputTypeIndex) {
  120. const inputType = getInputType(inputTypeIndex)
  121. if (inputType.key === 'hex') return parseHexBytes(dataText)
  122. if (inputType.key === 'base64') return parseBase64Bytes(dataText)
  123. return stringToUtf8Bytes(dataText)
  124. }
  125. function splitBinaryResult(value) {
  126. const text = String(value || '--')
  127. if (text === '--' || text.length <= 32) return [
  128. {
  129. id: 'bin-line-0',
  130. text
  131. }
  132. ]
  133. const lineLength = Math.ceil(text.length / 2)
  134. return [
  135. {
  136. id: 'bin-line-0',
  137. text: text.slice(0, lineLength)
  138. },
  139. {
  140. id: 'bin-line-1',
  141. text: text.slice(lineLength)
  142. }
  143. ]
  144. }
  145. function getConfigFromState(state) {
  146. const preset = (state.crcPresetOptions || [])[Number(state.crcPresetIndex)] || {}
  147. return {
  148. init: state.crcInitialValue,
  149. key: preset.key || '',
  150. poly: state.crcPoly,
  151. reflectIn: !!state.crcReflectIn,
  152. reflectOut: !!state.crcReflectOut,
  153. useLookupTable: !!preset.key && !preset.custom,
  154. width: state.crcWidth,
  155. xorOut: state.crcXorOut
  156. }
  157. }
  158. function getHashConfigFromState(state) {
  159. const preset = (state.crcPresetOptions || [])[Number(state.crcPresetIndex)] || {}
  160. return {
  161. hmacKey: state.crcHmacKey,
  162. key: preset.key || '',
  163. pbkdf2Iterations: state.crcPbkdf2Iterations,
  164. pbkdf2Length: state.crcPbkdf2Length,
  165. pbkdf2Salt: state.crcPbkdf2Salt
  166. }
  167. }
  168. function calculateFromState(state, fileBytes) {
  169. const bytes = fileBytes
  170. ? Array.prototype.slice.call(fileBytes)
  171. : parseInputBytes(state.crcDataText, state.crcInputTypeIndex)
  172. const preset = (state.crcPresetOptions || [])[Number(state.crcPresetIndex)] || {}
  173. const result = (preset.kind || 'crc') === 'crc'
  174. ? calculateCrc(bytes, getConfigFromState(state))
  175. : calculateHash(bytes, getHashConfigFromState(state))
  176. return {
  177. crcDataLengthText: formatBytes(bytes.length),
  178. crcErrorText: '',
  179. crcResultBase64: result.base64,
  180. crcResultBin: result.bin,
  181. crcResultBinLines: splitBinaryResult(result.bin),
  182. crcResultHex: result.hex
  183. }
  184. }
  185. module.exports = {
  186. calculateFromState,
  187. createInitialState,
  188. createPresetState,
  189. CRC_CONFIG_FIELDS,
  190. getCustomPresetIndex
  191. }