日常练习 - 汇编写base64加密函数

偷个懒,我是用vs内联汇编写的,不过大同小异了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <stdio.h>
#include <windows.h>
char base[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
void base64enc_asm(char * m, char * c){
int j;
__asm{
mov dword ptr[j], 0
while_start:
mov eax, dword ptr[m]
mov al, byte ptr[eax]
test al,al
je while_end
shr al, 2
and eax,0xff
mov ecx, dword ptr[j]
mov bl, byte ptr[base + eax]
mov eax, dword ptr[c]
mov byte ptr[eax + ecx], bl
mov eax, dword ptr[m]
mov al, byte ptr[eax]
and al,3
shl al,4
mov ebx, dword ptr[m]
mov ah, byte ptr[ebx+1]
shr ah,4
add al,ah
and eax,0xff
mov ecx, dword ptr[j]
mov bl, byte ptr[base + eax]
mov eax, dword ptr[c]
mov byte ptr[eax + ecx + 1], bl
mov eax, dword ptr[m]
mov al, byte ptr[eax+1]
cmp al,0
jne cj2
mov ecx, dword ptr[j]
mov eax, dword ptr[c]
mov byte ptr[eax + ecx + 2], 61
mov byte ptr[eax + ecx + 3], 61
jmp while_end
cj2:
mov eax, dword ptr[m]
mov al, byte ptr[eax + 1]
and al, 0xf
shl al, 2
mov ebx, dword ptr[m]
mov ah, byte ptr[ebx + 2]
shr ah, 6
add al, ah
and eax, 0xff
mov ecx, dword ptr[j]
mov bl, byte ptr[base + eax]
mov eax, dword ptr[c]
mov byte ptr[eax + ecx + 2], bl
mov eax, dword ptr[m]
mov al, byte ptr[eax + 2]
cmp al, 0
jne cj3
mov ecx, dword ptr[j]
mov eax, dword ptr[c]
mov byte ptr[eax + ecx + 3], 61
jmp while_end
cj3:
mov eax, dword ptr[m]
mov al, byte ptr[eax+2]
and eax, 0x3f
mov ecx, dword ptr[j]
mov bl, byte ptr[base + eax]
mov eax, dword ptr[c]
mov byte ptr[eax + ecx + 3], bl
mov eax, dword ptr[m]
add eax,3
mov dword ptr[m],eax
mov ecx, dword ptr[j]
add ecx,4
mov dword ptr[j],ecx
jmp while_start
while_end:
}
}
void base64enc(char * m, char * c){
int j = 0;
while (1){
if (*m == 0){
break;
}
c[j] = base[*m >> 2];
c[j + 1] = base[((*m & 3) << 4) + (*(m + 1) >> 4)];
if (*(m + 1) == 0){
c[j + 3] = c[j + 2] = '=';
break;
}
c[j + 2] = base[((*(m + 1) & 0xf) << 2) + (*(m + 2) >> 6)];
if (*(m + 2) == 0){
c[j + 3] = '=';
break;
}
c[j + 3] = base[*(m + 2) & 0x3f];
m += 3;
j += 4;
}
}
int main(void){
char * m = "hello,world!";
char c[100] = { 0 };
base64enc(m, c);
printf("%s\n", c);
system("pause");
return 0;
}

函数写的不精简,可能还有小bug,有空再修吧。