# 从汇编分析反推加密算法 #1

Closed
opened this Issue Jun 1, 2013 · 0 comments

 汇编代码 ``````MOV AL,BYTE PTR DS:[ESI+EDI] MOV CL,AL MOV DL,AL SHR CL,1 AND CL,40 AND DL,10 OR CL,DL MOV DL,AL SHR CL,2 AND DL,42 MOV BL,AL OR CL,DL MOV DL,AL AND DL,0F9 AND BL,20 SHL DL,3 OR DL,BL AND AL,4 SHR CL,1 SHL DL,1 OR CL,DL OR CL,AL MOV BYTE PTR DS:[ESI+EDI],CL `````` 翻译成伪代码 ```C = A D = A C = C >> 1 C = C & 01000000 D = D & 00010000 C = C | D D = A C = C >> 2 D = D & 01000010 B = A C = C | D D = A D = D & 11111001 B = B & 00100000 D = D << 3 D = D | B A = A & 00000100 C = C >> 1 D = D << 1 C = C | D C = C | A``` 合并等式 ```C = ((A >> 1) & 01000000) | (A & 00010000) C = (C >> 2) | (A & 01000010) D = ((A & 11111001) << 3) | (A & 00100000) C = (C >> 1) | (D << 1) | (A & 00000100)``` 将最外层的 `|` 运算拆分步骤 ```C = ((A >> 1) & 01000000) C = C | (A & 00010000) C = (C >> 2) | (A & 01000010) C = (C >> 1) | ((A & 11111001) << 4) C = C | (A & 00100000) << 1 C = C | (A & 00000100)``` 移动移位运算符 ```C = (A >> 4) & 00001000 C = C | (A & 00010000) >> 3 C = C | (A & 01000010) >> 1 C = C | (A & 11111001) << 4 C = C | (A & 00100000) << 1 C = C | (A & 00000100)``` 解开第一行的 `A >> 4`、解开 `&` 运算 ```= (A & 10000000) >> 4 | (A & 01000000) >> 1 | (A & 00100000) << 1 | (A & 00010000) >> 3 | (A & 00001000) << 4 | (A & 00000100) | (A & 00000010) >> 1 | (A & 00000001) << 4``` 假如给一个字节的 8 个位按顺序编号 `ABCDEFGH` 的话，由此不难理解，此算法的本质是将 `ABCDEFGH` 重排为 `ECBHAFDG`。 最终代码 ```function encrypt (buffer) { var result = new Buffer(buffer.length) for (var i = 0; i < buffer.length; i++) { result[i] = (buffer[i] & 0x80) >> 4 | (buffer[i] & 0x40) >> 1 | (buffer[i] & 0x20) << 1 | (buffer[i] & 0x10) >> 3 | (buffer[i] & 0x08) << 4 | (buffer[i] & 0x04) | (buffer[i] & 0x02) >> 1 | (buffer[i] & 0x01) << 4 } return result }```