echo "*" 用于在 crystal-lang 中输入的密码

echo "*" for passwords input in crystal-lang

有没有办法在处理密码时回显“*”或其他一些字符?使用 STDIN.noecho 有效但不提供任何用户反馈。 console.cr只提供raw和noecho。

谢谢。还在寻找...

你在 STDIN.noecho! 的正确道路上实际上你需要做的是在原始模式下从 STDIN 读取并在每次按下键时回显 *。然后你会监听 backspace,这样你就可以将光标向后移动一个并替换为 space,然后当用户键入另一个字符时将 space 替换为 *。您还需要检查终端捕获时按下的 enterControl+C 并以原始模式将其全部提供给您。

我基于用户 Alfe 在第二条评论中 here 发现的 bash 实现。 更新: 将代码更改为块内,希望能消除可能的终端问题。

# Fix for crystal bug
STDIN.blocking = true

# STDIN chars without buffering
STDIN.raw do
    # Dont echo out to the terminal
    STDIN.noecho do
        final_password = ""
        while char = STDIN.read_char
            # If we have a backspace
            if char == '\u{7f}'
                # Move the cursor back 1 char
                if final_password != ""
                    STDOUT << "\b \b"
                    STDOUT.flush
                    final_password = final_password[0...-1]
                end
                next
            elsif char == '\r'
                # Enter was pressed we're finished!
                break
            elsif char == '\u{3}'
                # Control + C was pressed. Get outta here
                Process.exit 0
            elsif char.ascii_control?
                # A Control + [] char was pressed. Not valid for a password
                next
            end

            STDOUT << "*"
            STDOUT.flush
            final_password += char
        end

        puts final_password
    end
end

# Resetting when finished
STDIN.blocking = false

如果对您有帮助,请务必标记为已回答!