Search code examples
perlmaskperl-modulemod-perl

unable to take 0 as password input using Win32::Console


I am new to this field. I am using the below code to mask password. it working fine but having issue while taking a password which has 0 (e.x. Pass012) in it.

As soon as I am entering 0 this script is exiting. it is not at all taking 0 as input. I tried to find out the reason and it seems my $Data = $handle->InputChar(1)) is unable to read 0, I am not sure why.

can anyone please dig into this code let me know what might be the issue here and how I can take 0 as a password input ?

#!/usr/bin/perl
use Win32::Console;


use strict; use warnings;
use Win32::Console;

run();

sub run {
    my $StdIn = Win32::Console->new(STD_INPUT_HANDLE);
    $StdIn->Mode(ENABLE_PROCESSED_INPUT);

    my $Password = prompt_password($StdIn, "Enter Password: ", '*');

    print "\n$Password";

    return;
}

sub prompt_password {
    my ($handle, $prompt, $mask) = @_;
    my ($Password);

    local $| = 1;
    print $prompt;

    $handle->Flush;

    while (my $Data = $handle->InputChar(1)) {
        last if "\r" eq $Data;

        if ("\ch" eq $Data ) {
            if ( "" ne chop( $Password )) {
                print "\ch \ch";
            }
            next;
        }

        $Password .= $Data;
        print $mask;
    }

    return $Password;
}

Solution

  • The string "0" is a false value in Perl, so this condition

    $Data = $handle->InputChar(1)
    

    is false when $handle->InputChar(1) returns the "0" string. Maybe a better check is whether the input does not match the empty string:

    while ((my $Data = $handle->InputChar(1)) ne "") { ...