【问题标题】:How to compare two strings in nasm assembler with test or cmp correctly (x64)如何正确比较 nasm 汇编器中的两个字符串与 test 或 cmp (x64)
【发布时间】:2020-04-13 16:24:55
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 你比较的是passwdinput的地址,而不是它们的内容。显然,地址总是不同的。您需要手动比较这些字符串的内容。
  • @fuz 哦,好的,你能发布一个答案来说明如何做到这一点吗?
  • 这个question 可能很有趣并且已经包含正确的代码(使用repe cmpsb)。然而,它不是完全重复的。
  • 另请注意,您没有为input 保留任何空间。

标签: assembly x86-64 nasm


【解决方案1】:

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

您可以使用显式循环来做到这一点:

        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

详见指令集参考。

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多