New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
xingrz opened this Issue Jun 1, 2013 · 0 comments

Comments

Projects
None yet
1 participant
@xingrz
Owner

xingrz commented Jun 1, 2013

汇编代码

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
}

@xingrz xingrz closed this Jun 1, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment