温馨提示:本文翻译自stackoverflow.com,查看原文请点击:assembly - How to compare two strings in nasm assembler with test or cmp correctly (x64)
assembly nasm x86-64

assembly - 如何在nasm汇编器中使用test或cmp正确比较两个字符串(x64)

发布于 2020-07-08 20:38:29

我想在nasm中进行简单的密码检查,但是我的程序从不跳转到correct_func,但是密码正确。难道我做错了什么?

section .data
    msg1: db "Enter your password: ", 0
    len1 equ $-msg1
    correct: db "Correct!", 0x0a
    lenc equ $-correct
    wrong: db "Wrong!", 0x0a
    lenw equ $-wrong
    passwd: db "ASD123"
    input

section .text
global _start

correct_func:
    mov rax, 0x1
    mov rdi, 1
    mov rsi, correct
    mov rdx, lenc
    syscall
    mov rax, 60
    mov rdi, 0
    syscall
    ret

_start:
    mov rax, 0x1
    mov rdi, 1
    mov rsi, msg1
    mov rdx, len1
    syscall
    mov rax, 0x0
    mov rdi, 0
    mov rsi, input
    mov rdx, 6
    syscall
    mov rax, passwd
    mov rbx, input
    cmp rax, rbx
    je correct_func
    mov rax, 0x1
    mov rdi, 1
    mov rsi, wrong
    mov rdx, lenw
    syscall
    mov rax, 60
    mov rdi, 0
    syscall

查看更多

提问者
BitFriends
被浏览
6
fuz 2020-04-14 01:09

要比较两个字符串,请将一个字符串的每个字符与另一个字符串的相应字符进行比较。如果两个字符串的长度相同且所有字符都匹配,则它们相等。我假设您检查了两者的长度是否相同。

您可以使用显式循环来执行此操作:

        mov ecx, 0            ; index and loop counter
.loop:  mov al, [passwd+rcx]  ; load a character from passwd
        cmp al, [input+rcx]   ; is it equal to the same character in the input?
        jne .incorrect        ; if not, the password is incorrect
        inc ecx               ; advance index
        cmp ecx, 6            ; reached the end of the string?
        jle .loop             ; loop until we do
                              ; if this line is reached, the password was correct

或者,您可以使用以下cmpsb说明:

        mov rsi, passwd       ; load the address of passwd
        mov rdi, input        ; load the address of input
        mov ecx, 6            ; load the string length
        repe cmpsb            ; compare the strings
        je correct_func       ; jump to correct_func if they are equal
                              ; if this line is reached, the password was wrong

有关详细信息,请参见指令集参考。