sm4.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. const UINT8_BLOCK = 16
  2. const Sbox = Uint8Array.from([
  3. 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
  4. 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
  5. 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
  6. 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
  7. 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
  8. 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35,
  9. 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87,
  10. 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e,
  11. 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1,
  12. 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
  13. 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f,
  14. 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51,
  15. 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8,
  16. 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0,
  17. 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
  18. 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48
  19. ])
  20. const CK = Uint32Array.from([
  21. 0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
  22. 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
  23. 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
  24. 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
  25. 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
  26. 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
  27. 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
  28. 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279
  29. ])
  30. const FK = Uint32Array.from([
  31. 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc
  32. ])
  33. const Crypt = {
  34. /**
  35. * Converts a JS string to an UTF-8 uint8array.
  36. *
  37. * @static
  38. * @param {String} str 16-bit unicode string.
  39. * @return {Uint8Array} UTF-8 Uint8Array.
  40. * @memberof Crypt
  41. */
  42. stringToArrayBufferInUtf8 (str) {
  43. // always utf-8
  44. const encoder = new TextEncoder()
  45. return encoder.encode(str)
  46. },
  47. /**
  48. * Converts an UTF-8 uint8array to a JS string.
  49. *
  50. * @static
  51. * @param {Uint8Array} strBuffer UTF-8 Uint8Array.
  52. * @return {String} 16-bit unicode string.
  53. * @memberof Crypt
  54. */
  55. utf8ArrayBufferToString (strBuffer) {
  56. const decoder = new TextDecoder('utf-8')
  57. return decoder.decode(strBuffer)
  58. }
  59. }
  60. export default class SM4 {
  61. /**
  62. * Creates an instance of SM4.
  63. * @param {Object} config
  64. * @memberof SM4
  65. */
  66. constructor (config) {
  67. const keyBuffer = typeof config.key === 'string' ? Crypt.stringToArrayBufferInUtf8(config.key) : Uint8Array.from(config.key)
  68. if (keyBuffer.length !== 16) {
  69. throw new Error('key should be a 16 bytes string')
  70. }
  71. /**
  72. * key should be 16 bytes string
  73. * @member {Uint8Array} key
  74. */
  75. this.key = keyBuffer
  76. /**
  77. * iv also should be 16 bytes string
  78. * @member {Uint8Array} iv
  79. */
  80. let ivBuffer = new Uint8Array(0)
  81. if (config.iv !== undefined && config.iv !== null) {
  82. // need iv
  83. ivBuffer = Crypt.stringToArrayBufferInUtf8(config.iv)
  84. if (ivBuffer.length !== 16) {
  85. throw new Error('iv should be a 16 bytes string')
  86. }
  87. }
  88. this.iv = ivBuffer
  89. /**
  90. * sm4's encrypt mode
  91. * @member {Enum} mode
  92. */
  93. this.mode = 'ecb'
  94. if (['cbc', 'ecb'].includes(config.mode)) {
  95. // set encrypt mode. default is ecb
  96. this.mode = config.mode
  97. }
  98. /**
  99. * sm4's cipher data type
  100. * @member {Enum} outType
  101. */
  102. this.cipherType = 'uint8array'
  103. if (['uint8array', 'text'].includes(config.outType)) {
  104. // set data type. default is uint8array
  105. this.cipherType = config.outType
  106. }
  107. /**
  108. * sm4's encrypt round key array
  109. * @member {Uint32Array} encryptRoundKeys
  110. */
  111. this.encryptRoundKeys = new Uint32Array(32)
  112. // spawn 32 round keys
  113. this.spawnEncryptRoundKeys()
  114. /**
  115. * sm4's decrypt round key array
  116. * @member {Uint32Array} encryptRoundKeys
  117. */
  118. this.decryptRoundKeys = Uint32Array.from(this.encryptRoundKeys)
  119. this.decryptRoundKeys.reverse()
  120. }
  121. /**
  122. * general sm4 encrypt/decrypt algorithm for a 16 bytes block using roundKey
  123. *
  124. * @param {Uint32Array} blockData
  125. * @param {Uint32Array} roundKeys
  126. * @return {Uint32Array} return a 16 bytes cipher block
  127. * @memberof SM4
  128. */
  129. doBlockCrypt (blockData, roundKeys) {
  130. const xBlock = new Uint32Array(36)
  131. xBlock.set(blockData, 0)
  132. // loop to process 32 rounds crypt
  133. for (let i = 0; i < 32; i++) {
  134. xBlock[i + 4] = xBlock[i] ^ this.tTransform1(xBlock[i + 1] ^ xBlock[i + 2] ^ xBlock[i + 3] ^ roundKeys[i])
  135. }
  136. const yBlock = new Uint32Array(4)
  137. // reverse last 4 xBlock member
  138. yBlock[0] = xBlock[35]
  139. yBlock[1] = xBlock[34]
  140. yBlock[2] = xBlock[33]
  141. yBlock[3] = xBlock[32]
  142. return yBlock
  143. }
  144. /**
  145. * spawn round key array for encrypt. reverse this key array when decrypt.
  146. * every round key's length is 32 bytes.
  147. * there are 32 round keys.
  148. * @return {Uint32Array}
  149. * @memberof SM4
  150. */
  151. spawnEncryptRoundKeys () {
  152. // extract mk in key
  153. const mk = new Uint32Array(4)
  154. mk[0] = this.key[0] << 24 | this.key[1] << 16 | this.key[2] << 8 | this.key[3]
  155. mk[1] = this.key[4] << 24 | this.key[5] << 16 | this.key[6] << 8 | this.key[7]
  156. mk[2] = this.key[8] << 24 | this.key[9] << 16 | this.key[10] << 8 | this.key[11]
  157. mk[3] = this.key[12] << 24 | this.key[13] << 16 | this.key[14] << 8 | this.key[15]
  158. // calculate the K array
  159. const k = new Uint32Array(36)
  160. k[0] = mk[0] ^ FK[0]
  161. k[1] = mk[1] ^ FK[1]
  162. k[2] = mk[2] ^ FK[2]
  163. k[3] = mk[3] ^ FK[3]
  164. // loop to spawn 32 round keys
  165. for (let i = 0; i < 32; i++) {
  166. k[i + 4] = k[i] ^ this.tTransform2(k[i + 1] ^ k[i + 2] ^ k[i + 3] ^ CK[i])
  167. this.encryptRoundKeys[i] = k[i + 4]
  168. }
  169. }
  170. /**
  171. * left rotate x by y bits
  172. *
  173. * @param {*} x
  174. * @param {Number} y
  175. * @returns
  176. * @memberof SM4
  177. */
  178. rotateLeft (x, y) {
  179. return x << y | x >>> (32 - y)
  180. }
  181. /**
  182. * L transform function for encrypt
  183. *
  184. * @param {Uint32Number} b
  185. * @returns {Uint32Number}
  186. * @memberof SM4
  187. */
  188. linearTransform1 (b) {
  189. return b ^ this.rotateLeft(b, 2) ^ this.rotateLeft(b, 10) ^ this.rotateLeft(b, 18) ^ this.rotateLeft(b, 24)
  190. }
  191. /**
  192. * L' transform function for key expand
  193. *
  194. * @param {Uint32Number} b
  195. * @returns {Uint32Number}
  196. * @memberof SM4
  197. */
  198. linearTransform2 (b) {
  199. return b ^ this.rotateLeft(b, 13) ^ this.rotateLeft(b, 23)
  200. }
  201. /**
  202. * τ transform function
  203. *
  204. * @param {Uint32Number} a
  205. * @returns {Uint32Number}
  206. * @memberof SM4
  207. */
  208. tauTransform (a) {
  209. return Sbox[a >>> 24 & 0xff] << 24 | Sbox[a >>> 16 & 0xff] << 16 | Sbox[a >>> 8 & 0xff] << 8 | Sbox[a & 0xff]
  210. }
  211. /**
  212. * mix replacement T transform for encrypt
  213. *
  214. * @param {Uint32Number} z
  215. * @returns {Uint32Number}
  216. * @memberof SM4
  217. */
  218. tTransform1 (z) {
  219. const b = this.tauTransform(z)
  220. const c = this.linearTransform1(b)
  221. return c
  222. }
  223. /**
  224. * mix replacement T transform for key expand
  225. *
  226. * @param {Uint32Number} z
  227. * @returns {Uint32Number}
  228. * @memberof SM4
  229. */
  230. tTransform2 (z) {
  231. const b = this.tauTransform(z)
  232. const c = this.linearTransform2(b)
  233. return c
  234. }
  235. /**
  236. * padding the array length to multiple of BLOCK
  237. *
  238. * @param {ByteArray} originalBuffer
  239. * @returns {ByteArray}
  240. * @memberof SM4
  241. */
  242. padding (originalBuffer) {
  243. if (originalBuffer === null) {
  244. return null
  245. }
  246. const paddingLength = UINT8_BLOCK - originalBuffer.length % UINT8_BLOCK
  247. const paddedBuffer = new Uint8Array(originalBuffer.length + paddingLength)
  248. paddedBuffer.set(originalBuffer, 0)
  249. paddedBuffer.fill(paddingLength, originalBuffer.length)
  250. return paddedBuffer
  251. }
  252. /**
  253. * depadding the byte array to its original length
  254. *
  255. * @param {ByteArray} paddedBuffer
  256. * @returns {ByteArray}
  257. * @memberof SM4
  258. */
  259. dePadding (paddedBuffer) {
  260. if (paddedBuffer === null) {
  261. return null
  262. }
  263. const paddingLength = paddedBuffer[paddedBuffer.length - 1]
  264. const originalBuffer = paddedBuffer.slice(0, paddedBuffer.length - paddingLength)
  265. return originalBuffer
  266. }
  267. /**
  268. * exctract uint32 array block from uint8 array
  269. *
  270. * @param {Uint8Array} uint8Array
  271. * @param {Number} baseIndex
  272. * @returns {Uint32Array}
  273. * @memberof SM4
  274. */
  275. uint8ToUint32Block (uint8Array, baseIndex = 0) {
  276. const block = new Uint32Array(4)// make Uint8Array to Uint32Array block
  277. block[0] = uint8Array[baseIndex] << 24 | uint8Array[baseIndex + 1] << 16 | uint8Array[baseIndex + 2] << 8 | uint8Array[baseIndex + 3]
  278. block[1] = uint8Array[baseIndex + 4] << 24 | uint8Array[baseIndex + 5] << 16 | uint8Array[baseIndex + 6] << 8 | uint8Array[baseIndex + 7]
  279. block[2] = uint8Array[baseIndex + 8] << 24 | uint8Array[baseIndex + 9] << 16 | uint8Array[baseIndex + 10] << 8 | uint8Array[baseIndex + 11]
  280. block[3] = uint8Array[baseIndex + 12] << 24 | uint8Array[baseIndex + 13] << 16 | uint8Array[baseIndex + 14] << 8 | uint8Array[baseIndex + 15]
  281. return block
  282. }
  283. /**
  284. * encrypt the string plaintext
  285. *
  286. * @param {String} plaintext
  287. * @memberof SM4
  288. * @return {Unit8Array|String} cipherByteArray
  289. */
  290. encrypt (plaintext) {
  291. const plainByteArray = Crypt.stringToArrayBufferInUtf8(plaintext)
  292. const padded = this.padding(plainByteArray)
  293. const blockTimes = padded.length / UINT8_BLOCK
  294. const outArray = new Uint8Array(padded.length)
  295. if (this.mode === 'cbc') {
  296. // CBC mode
  297. if (this.iv === null || this.iv.length !== 16) {
  298. throw new Error('iv error')
  299. }
  300. // init chain with iv (transform to uint32 block)
  301. let chainBlock = this.uint8ToUint32Block(this.iv)
  302. for (let i = 0; i < blockTimes; i++) {
  303. // extract the 16 bytes block data for this round to encrypt
  304. const roundIndex = i * UINT8_BLOCK
  305. const block = this.uint8ToUint32Block(padded, roundIndex)
  306. // xor the chain block
  307. chainBlock[0] = chainBlock[0] ^ block[0]
  308. chainBlock[1] = chainBlock[1] ^ block[1]
  309. chainBlock[2] = chainBlock[2] ^ block[2]
  310. chainBlock[3] = chainBlock[3] ^ block[3]
  311. // use chain block to crypt
  312. const cipherBlock = this.doBlockCrypt(chainBlock, this.encryptRoundKeys)
  313. // make the cipher block be part of next chain block
  314. chainBlock = cipherBlock
  315. for (let l = 0; l < UINT8_BLOCK; l++) {
  316. outArray[roundIndex + l] = cipherBlock[parseInt(l / 4)] >> ((3 - l) % 4 * 8) & 0xff
  317. }
  318. }
  319. } else {
  320. // this will be ECB mode
  321. for (let i = 0; i < blockTimes; i++) {
  322. // extract the 16 bytes block data for this round to encrypt
  323. const roundIndex = i * UINT8_BLOCK
  324. const block = this.uint8ToUint32Block(padded, roundIndex)
  325. const cipherBlock = this.doBlockCrypt(block, this.encryptRoundKeys)
  326. for (let l = 0; l < UINT8_BLOCK; l++) {
  327. outArray[roundIndex + l] = cipherBlock[parseInt(l / 4)] >> ((3 - l) % 4 * 8) & 0xff
  328. }
  329. }
  330. }
  331. if (this.cipherType === 'text') {
  332. return Crypt.utf8ArrayBufferToString(outArray)
  333. }
  334. return outArray
  335. }
  336. /**
  337. * decrypt the Unit8Array cipherByteArray
  338. *
  339. * @param {String|Unit8Array} cipherByteArray
  340. * @memberof SM4
  341. */
  342. decrypt (cipherObj) {
  343. let cipherByteArray
  344. if (typeof cipherObj === 'string') {
  345. cipherByteArray = Crypt.stringToArrayBufferInUtf8(cipherObj)
  346. } else {
  347. cipherByteArray = cipherObj
  348. }
  349. const blockTimes = cipherByteArray.length / UINT8_BLOCK
  350. const outArray = new Uint8Array(cipherByteArray.length)
  351. // decrypt the cipherByteArray by block
  352. if (this.mode === 'cbc') {
  353. // todo CBC mode
  354. if (this.iv === null || this.iv.length !== 16) {
  355. throw new Error('iv error')
  356. }
  357. // init chain with iv (transform to uint32 block)
  358. let chainBlock = this.uint8ToUint32Block(this.iv)
  359. for (let i = 0; i < blockTimes; i++) {
  360. // extract the 16 bytes block data for this round to encrypt
  361. const roundIndex = i * UINT8_BLOCK
  362. // make Uint8Array to Uint32Array block
  363. const block = this.uint8ToUint32Block(cipherByteArray, roundIndex)
  364. // reverse the round keys to decrypt
  365. const plainBlockBeforeXor = this.doBlockCrypt(block, this.decryptRoundKeys)
  366. // xor the chain block
  367. const plainBlock = new Uint32Array(4)
  368. plainBlock[0] = chainBlock[0] ^ plainBlockBeforeXor[0]
  369. plainBlock[1] = chainBlock[1] ^ plainBlockBeforeXor[1]
  370. plainBlock[2] = chainBlock[2] ^ plainBlockBeforeXor[2]
  371. plainBlock[3] = chainBlock[3] ^ plainBlockBeforeXor[3]
  372. // make the cipher block be part of next chain block
  373. chainBlock = block
  374. for (let l = 0; l < UINT8_BLOCK; l++) {
  375. outArray[roundIndex + l] = plainBlock[parseInt(l / 4)] >> ((3 - l) % 4 * 8) & 0xff
  376. }
  377. }
  378. } else {
  379. // ECB mode
  380. for (let i = 0; i < blockTimes; i++) {
  381. // extract the 16 bytes block data for this round to encrypt
  382. const roundIndex = i * UINT8_BLOCK
  383. // make Uint8Array to Uint32Array block
  384. const block = this.uint8ToUint32Block(cipherByteArray, roundIndex)
  385. // reverse the round keys to decrypt
  386. const plainBlock = this.doBlockCrypt(block, this.decryptRoundKeys)
  387. for (let l = 0; l < UINT8_BLOCK; l++) {
  388. outArray[roundIndex + l] = plainBlock[parseInt(l / 4)] >> ((3 - l) % 4 * 8) & 0xff
  389. }
  390. }
  391. }
  392. // depadding the decrypted data
  393. const depaddedPlaintext = this.dePadding(outArray)
  394. // transform data to utf8 string
  395. return Crypt.utf8ArrayBufferToString(depaddedPlaintext)
  396. }
  397. }