Leggi una password


20

La tua sfida è leggere una "password" dalla tastiera / input standard.

Sfida :

  • Leggi una stringa in modo sinvisibile.
  • Per ciascuno dei personaggi in s, stampa un personaggio c.
  • In tempo reale.

Regole:

  • Devi stampare cin tempo reale. Non appena l'utente immette un carattere, è necessario visualizzarlo c.
  • c deve essere costante, ovvero deve avere lo stesso carattere.
  • cpuò essere qualsiasi carattere visibile (ovvero non può essere una nuova riga, spazio, tabulazione o non stampabile).
  • cnon può essere basato su s, cioè cdeve essere definito / costante prima di sessere letto.
  • c deve essere lo stesso ogni volta che si esegue il programma.
  • cpuò essere uno dei personaggi sse per caso, purché vengano seguite tutte le altre regole.
  • Nessuno dei personaggi di spuò apparire sullo schermo, ctranne (vedi regola precedente).
  • È possibile utilizzare qualsiasi metodo ragionevole di input e output purché vengano seguite tutte le altre regole.
  • Si può presumere che la lunghezza di snon sia mai più lunga della larghezza della finestra terminale / grafica.
  • Se si utilizza un terminale, il programma dovrebbe terminare dopo aver inserito una nuova riga o EOF.

Esempio :

Se sfosse password01ed cera *, l'output sarebbe simile a:

password

Vincitore :

Vince l'invio più breve in ogni lingua.


Python è tkinterammesso per il nostro campo di input personalizzato (come quello in HTML), in modo tale che il programma non termina quando si preme Invio, ma quando si chiude la Entryfinestra (X su Windows e cmd+ Wsu Mac)?
Mr. Xcoder,

@ Mr.Xcoder Sì, è valido.
MD XF,

Possiamo usare Ctrl + J per rappresentare una nuova riga letterale nel terminale? In alternativa, possiamo usare Ctrl + Z invece di invio?
Conor O'Brien,

@ ConorO'Brien Chiarire come dovrebbe terminare l'input nel terminale.
MD XF,

2
Cosa dovrebbe succedere se l'utente preme backspace?
zdimension,

Risposte:


6

str , 5 byte

n=?,1

A causa di un bug, si tratta di 5 byte. Dovrebbe essere solo 1 byte:

1

Execution of <code>n=?,1</code>


Sicuramente ho visto la cmderrisposta arrivare a causa del tuo Ctrl+Zcommento: P
MD XF

10/10 strumento giusto per il lavoro
Erik the Outgolfer

20

HTML, 20 byte

<input type=password


Alternativa: HTML + JavaScript, 51 byte

Sebbene l'OP abbia confermato che è valido, ecco una soluzione che utilizza JS per i puristi!

<input id=i oninput=i.value=i.value.replace(/./g,8)


4
FGITW, qualcuno? : P (lo prese letteralmente dieci secondi)
MD XF

oninput=_=>i.value=i.value.replace(/./g,"*")salva un byte.
Arjun,

Dato che cpuò essere qualsiasi cosa, puoi salvare altri due byte cononinput=_=>i.value=i.value.replace(/./g,1)
Arjun,

Mi preoccuperò che se (quando) qualcuno dichiarasse la mia soluzione solo HTML non valida, @Arjun;) Avrei solo lanciato il JS insieme per placare alcune persone!
Shaggy,

6
Dov'è la spiegazione, non capisco.
Magic Octopus Urn

11

Vim, 36 byte:

:im <C-v><CR> <C-v><esc>ZQ<CR>:au I<tab><tab> * let v:char=0<CR>i

Questo utilizza VIM-chiave notazione , quindi <C-v>è control-v , <CR>è entrare, <esc>è la chiave di fuga, ed <tab>è la chiave tab.

c è '0'.

Ecco un hexdump per dimostrare che il conteggio dei byte è accurato:

00000000: 3a69 6d20 160a 2016 1b5a 510a 3a61 7520  :im .. ..ZQ.:au 
00000010: 4909 0920 2a20 6c65 7420 763a 6368 6172  I.. * let v:char
00000020: 3d30 0a69                                =0.i

Funziona eseguendo i seguenti due ex comandi:

:imap <CR> <esc>ZQ
:autocmd InsertCharPre * let v:char=0

Il primo significa

:imap               " Anytime the following is pressed in insert mode:
      <CR>          "   (the 'enter' key)
           <esc>ZQ  " Then act as if the user instead pressed '<esc>ZQ' (close the buffer)

E il secondo significa

:autocmd                                " Automatically as vim runs:
         InsertCharPre                  "   Any time the user is about to insert a char
                       *                "   In any type of file
                         let v:char=0   "     Then instead insert a '0' character

Penso che non ci sia un modo per me di scendere a questo usando il mio metodo attuale senza ignorare almeno gli spazi .. Bella risposta!
nmjcman101,

o_O Questo è pulito ...
Mr. Xcoder il


6

Aceto , 8 7 6 byte

,!`XpO

Spiegazione:

Leggi un carattere ( ,), negalo ( !) ed esce condizionalmente. Stampa lo zero in cima alla pila ( p) e torna all'inizio.

Corri con -Fper vedere immediatamente l'effetto (perché arrossire)

La mia prima soluzione era basata sul post sandbox, con spazi consentiti come caratteri sostitutivi e non è necessario uscire su enter (4 byte):

,'p>

5

C su POSIX, 128 117 113 96 byte

-11 grazie a Quentin che cerca attraverso termios.h
-4 grazie a Quentin che sottolinea i miei stupidi errori
-17 perché Quentin è un mago spaventoso.

c,t[15];f(){for(tcgetattr(1,t),t[3]&=~10,tcsetattr(1,0,t);(c=getchar())^10&&c^4;)printf(".");}

Questo mette STDIN in modalità raw / invisibile in modo da poter ottenere i tasti premuti in tempo reale. Questo richiede 77 byte e sono sicuro di poterlo giocare un po '. Nota che questo non resetta STDIN all'uscita, quindi rovinerà il tuo terminale se non lo fai manualmente.

Ecco come è possibile ripristinare STDIN:

void stdin_reset(void)
{
    struct termios t;
    get_stdin(&t);
    t.c_lflag |= ECHO;
    t.c_lflag |= ICANON;
    set_stdin(&t);
}

Uscita come mostrato nella GIF :-)


1
Scavando nel mio termios.h, ECHOè 0000010ed ICANONè 0000002. Ciò significa che ~(ECHO|ICANON)è solo ~10:)
Quentin

@Quentin Edited! Saluti: D
MD XF

1
Inoltre, ognuno !=può essere sostituito con ^e '\n'con 10(assumendo UTF-8);)
Quentin

2
Se andiamo al completo UB, possiamo sostituire tla memoria con una matrice di numeri interi. Poi c_lcflagsfinisce t[3], e non abbiamo bisogno né del nome né del tipo né del #include, per un totale di 94 byte: c,t[15];f(){for(tcgetattr(1,t),t[3]&=~10,tcsetattr(1,0,t);(c=getchar())^10&&c^4;)printf(".");}- Ma forse faresti meglio a farmi pubblicare come risposta piuttosto che divertirmi con i tuoi :)
Quentin

1
@Quentin Oh ... mio. Sei un mago. E ho pensato di essere bravo in C ... se vuoi pubblicarlo come la tua risposta sentiti libero e annullerò le mie modifiche, altrimenti lo lascerò modificato nel mio.
MD XF,

4

codice macchina x86 su MS-DOS - 14 byte

Come al solito, questo è un file COM completo, che può essere eseguito su DosBox, oltre alla maggior parte delle varianti DOS.

00000000  b4 08 b2 2a cd 21 80 f4  0a 3c 0d 75 f7 c3        |...*.!...<.u..|
0000000e

Assemblaggio commentato:

    org 100h

section .text

start:
    mov ah,8h       ; ah starts at 08h (read console, no echo)
    mov dl,'*'      ; write asterisks (we could have left whatever
                    ; startup value we have here, but given that dx=cs,
                    ; we have no guarantee to get a non-zero non-space
                    ; value)
lop:
    ; this loop runs twice per character read: the first time with
    ; ah = 08h (read console, no echo syscall), the second time with
    ; ah = 02h (write console); a xor is used to switch from one
    ; mode to the other
    int 21h         ; perform syscall
    xor ah,0ah      ; switch syscall 08h <=> 02h
    cmp al,0dh      ; check if we read a newline (if we wrote stuff
                    ; we are just checking the last value read, so
                    ; no harm done; at the first iteration al starts
                    ; at 0, so no risk here)
    jne lop         ; loop if it wasn't a newline
quit:
    ret             ; quit

2
...non c'è modo. È stupefacente.
MD XF,

Grazie, ma sento che c'è ancora qualcos'altro da tagliare; che xorè un woppin' 3 byte, e sarebbe esattamente grande se ho fatto funzionare nel complesso ax; Ho provato xor ax,0a0dh/ test al,al, ma è altrettanto grande perché stupido testè di due byte, grrr ...
Matteo Italia,

3

Python 2 , 50 byte

from msvcrt import*
while'\r'!=getch():print'\b*',

Funziona solo su Windows


1
Purtroppo funziona solo su Windows: ((
Mr. Xcoder


3

Java 5-8, 125 122 131 124 byte

class X{public static void main(String[]a){new java.awt.Frame(){{add(new javax.swing.JPasswordField());setVisible(1>0);}};}}

Ungolfed:

class X{
    public static void main(String[]a){
        new java.awt.Frame(){
            {
                add(new javax.swing.JPasswordField());
                setVisible(1>0);
            }
        };
    }
}

Risultato:

enter image description here

Credito:

-3 @MD XF (sottolineato il mio stupido errore con String[]args)

-7 @KritixiLithos (sottolineato public classpuò essere class)


1
È String[]argsnecessario?
MD XF,

@MDXF se desidero dare la risposta per Java 8 ci sono MOLTE cose che potrei fare. Tuttavia, sto facendo di questo una risposta Java generica. Tuttavia, sì, posso farcela String[]a.
Magic Octopus Urn

Hai dimenticato di aggiornare la risposta golf. Inoltre, non 1>0valuta 1?
MD XF,

@MDXF in Java (< 8)- 1>0valuta true, che è diverso. Pubblicherò la stessa risposta in Groovy.
Magic Octopus Urn

@StephenS questa è una risposta Java generica, non una risposta Java 8.
Magic Octopus Urn

3

Mathematica 34 byte

 InputString["",FieldMasked->True];

Viene visualizzato un singolo asterisco, dopo aver digitato ciascun carattere. Le virgolette vuote sono per il titolo che appare nella finestra di input pop-up.

Questo ;impedisce la stampa della password.

enter image description here


Spazio iniziale intenzionale?
MD XF,

2

Vim, 58 50 52 50 byte

Aggiunto per assicurarsi che gestisse correttamente gli spazi.

Grazie a @DJMcMayhem per un sacco di aiuto e idee

i:im 32 *Y94pVGg
kWcW<Space>
:im 
 ZQ
dG@"qi

Nella tipica sintassi del tasto Vim di seguito. I caratteri contrassegnati come con un ^sono Ctrl+<char>, quindi ^Q=Ctrl+q

i:im ^V^V32 *^[Y94pVGg^A
kWcW<Space>^[
:im ^V
 ZQ
dG@"qi

Non esiste un collegamento TIO, perché avresti bisogno di inserire direttamente in Vim (al contrario di pre-immissione come normale). Per eseguire il codice è necessario digitarlo in Vim, quindi è possibile digitare la password e premere invio. Non farà nulla con la password. Non saprà nemmeno cosa fosse. Non appena si preme entra nella finestra di Vim:q!

Funziona mappando tutte le ASCII stampabili su *in modalità inserimento e mappando <CR>su<ESC>:q!<CR>


Forse chiarire quali sono i simboli? Penso che dovrebbero essere, <C-v>, <esc> and <C-a>ma è difficile da dire.
DJMcMayhem

@DJMcMayhem Lo farà. Per inciso, penso che puoi incollarli in Vim e verranno visualizzati in modo appropriato.
nmjcman101,


2

FLTK, 47 caratteri

Function{}{}{Fl_Window{}{}{Fl_Input{}{type 5}}}

Esecuzione di esempio:

bash-4.4$ fluid -c password.fl

bash-4.4$ fltk-config --compile password.cxx 
g++ -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -o 'password' 'password.cxx' -Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -lfltk -lX11

bash-4.4$ ./password 

Uscita campione:

password input in FLTK


2

Elaborazione, 53 byte

String a="";void draw(){text(keyPressed?a+=0:a,9,9);}

Questo prende input tramite i tasti premuti da una finestra grafica. Il personaggio con cui sceglie di rappresentare le password è 0. Si noti che a causa dell'elevato framerate, ogni pressione di un tasto apparirà come più 0s (e anche per il fatto che questo è keyPressede non keyTyped(non un valore booleano) o keyrelease).

gif


2

Bash , 54 byte

while read -eN1 c 2>&-;[[ ${c/$'\r'/} ]];do printf X;done

Ai fini del punteggio, $'\r'può essere sostituito con un ritorno a capo letterale.

Provalo online! (non c'è molto da vedere)


2

ZX81 BASIC, 54 byte

10 IF LEN INKEY$ THEN GOTO PI
30 IF NOT LEN INKEY$ THEN GOTO EXP PI
50 IF INKEY$>"Z" THEN STOP
70 PRINT "*";
90 GOTO PI

Nel set di caratteri ZX81 i caratteri stampabili si trovano nello spazio dell'intervallo su Z, sebbene in realtà non sia possibile inserire uno spazio in questo modo poiché è il carattere di interruzione.

ZX Spectrum BASIC, 24 byte

10 PAUSE NOT PI: IF INKEY$>=" " THEN PRINT "*";:GOTO PI

Si noti che >=conta come una parola chiave a byte singolo in Sinclair BASIC (in questo caso codepoint 140).


Sono necessari spazi tra i numeri di riga e le funzioni?
MD XF,

Potrebbe accorciare PRINTa ?, so che lavora in un sacco di vecchi dialetti BASIC
MD XF

@MDXF PRINTè un token da 1 byte, è appena rappresentato sullo schermo come i 7 caratteri (tranne dopo THEN, quando lo spazio iniziale è soppresso).
Neil,

2

R, 29 byte

invisible(openssl::askpass())

Integrato che gestisce le voci della password. Apre una nuova finestra e sostituisce l'input con punti. invisibleviene utilizzato per sopprimere la stampa della password su STDOUT.


2

Tcl / Tk, 18

gri [ent .e -sh *]

Deve essere eseguito nella shell interattiva (o avere le abbreviazioni abilitate):

enter image description here


21 byte senza le abbreviazioni del comando complicato: grid [entry .e -sh *]ed -shè un'abbreviazione dell'opzione per -show. 23 byte è ciò che considererei un minimo per un programma non golfabile che lo fa.
Donal Fellows,

2

Vim, 15 sequenze di tasti

:cal inp<S-tab>'')|q<cr>

<S-tab>significa shift + tab.

Apparentemente, c'è un elemento incorporato per questo di cui non ero a conoscenza. Dato che mi piace molto la mia risposta manuale e questo approccio è radicalmente diverso, ho pensato che avrei dovuto pubblicare una nuova risposta invece di modificarla.

Funziona chiamando la inputsecretfunzione, quindi si chiude immediatamente dopo la sua uscita.


2

6502 codice macchina (C64), 22 21 byte

0e 08 20 9f ff 20 e4 ff f0 f8 c9 0d f0 01 a9 60 20 d2 ff 50 ed

Utilizzo :SYS 2062

Elenco di disassemblaggio commentato (ACME), puoi decommentare le prime tre righe commentate da avviare RUNuna volta caricate:

!cpu 6502
!to "password2.prg",cbm
;* = $0801                               ; BASIC starts at #2049
;!byte $0d,$08,$dc,$07,$9e,$20,$32,$30   ; BASIC to load $c000
;!byte $36,$32,$00,$00,$00               ; inserts BASIC line: 2012 SYS 2062

    GETIN  =  $FFE4
    SCNKEY =  $FF9F
    CHROUT =  $FFD2

* = $080e
keyScan:
    jsr SCNKEY  ; get key
    jsr GETIN   ; put key in A

    beq keyScan ; if no key pressed loop    

    cmp #13     ; check if RETURN was pressed
    beq $081b   ; if true go to operand of next instruction (#$60 = rts)

    lda #$60    ; load char $60 into accumulator
    jsr CHROUT  ; print it

    bvc keyScan ; loop

Commenti:

  • Non ho trovato nulla nei documenti, ma sembra che, dopo la chiamata GETIN, beq si ramifichi solo dove non sono state registrate nuove pressioni di tasti;
  • Usando # $ 60 come carattere di output, quel byte può essere riutilizzato come istruzione "rts" quando si preme RETURN.

2

Forth (gforth) , 54 byte

: f begin key dup 4 - swap 13 - * while ." *" repeat ;

Spiegazione

begin      \ enters the loop
    key    \ waits for a single character as input, places ascii code of character on stack
    dup    \ duplicates the key value on the stack
    4 -    \ subtracts 4 from the key value (shorter way of checking for not equals)
    swap   \ swaps the top two stack values
    13 -   \ subtract 13 from the key value
    *      \ multiply top two stack values (shorter version of "and")
while      \ if top of stack is true, enter loop body, else exit loop
    ." *"  \ output *
repeat     \ go back to beginning of loop

1

Python 3 + tkinter- 63 61 byte

from tkinter import*
t=Tk();Entry(show=1).pack();t.mainloop()

Visualizza un 1per ogni carattere, termina quando si chiude la finestra (OP ha detto che è consentito).

Gif


Would from tkinter import* (newline) Entry(show=1).pack();Tk().mainloop() work?
Conor O'Brien

@ConorO'Brien testing
Mr. Xcoder

@ConorO'Brien no. It produces two different tkinter windows. One with the text field, one empty. It doesn't seem right to me.
Mr. Xcoder

Do you need the show=?
Esolanging Fruit

@Challenger5 Yes, we do need the show=
Mr. Xcoder

1

Groovy, 77 73 bytes

{new java.awt.Frame(){{add(new javax.swing.JPasswordField());visible=1}}}

This is an anonymous closure, with 0 required inputs.

Ungolfed:

{
    new java.awt.Frame() {
        {
            add(new javax.swing.JPasswordField())
            visible=1
        }
    }
}

Edit 1 (-4 bytes): Component#visible can be directly accessed, read more here.


1

Micro, 35 bytes

"":i{L46c:\
i~+:i
i10c=if(,a)}a
i:\

explination:

"":i                      create new blank string 'i'
    {                          begin input loop
     L                         input a character
      46c:\                    display ascii char #46 (.) (it is popped, leaving the input char from 'L'
           i~+:i               push i, flip i and the char around, concatinate them, and store that to i
                i10c=if(,a)}a  OK, a lot happens here, if a NL is in i, the loop terminates, and the final i:\ will display the input


1
That's a pretty good first attempt at a language! +1
MD XF

1

BF, 24 bytes

++++++[->++++++<],[>.<,]

Works with bf.doleczek.pl. You can send a zero char to the program with Ctrl+Z.

Alternative solution:

BF, 1 byte

,

This is a very tongue-in-cheek solution. My terminal is 0 characters wide, so please don't enter any passwords longer than that.


Whoa... not bad!
MD XF

@MDXF Are you referring to the 24 byte one or the 1 byte one?
Esolanging Fruit

Clearly the 24-byte one. I completely forgot that printing \b is a thing. :P
MD XF

@MDXF What do you mean by that? \b is unprintable anyways.
Esolanging Fruit

No I mean your solution uses \b to override the input, correct?
MD XF

1

PowerShell, 12 bytes

Read-Host -a

This reads input from host and, with the -a flag treats it as a securestring/password. In the ISE it pops up a message box which has a similar behavior since the ISE doesn't allow keypress capture.

PS C:\Windows\system32> Read-Host -a
************

1

QBasic, 48 bytes

DO
a$=INPUT$(1)
IF ASC(a$)=13THEN END
?"*";
LOOP

INPUT$(1) reads the next character from keyboard input. (This can include things like tab, backspace, and escape, but since the OP didn't say anything about those I'll assume we don't have to worry about them.) If the character is \r (ASCII 13), terminate the program; otherwise, print * without a newline. Repeat ad infinitum.


1

Perl + Bash, 30 bytes

print"*"while$|=1+`read -sn 1`

c is *, uses read from bash, so isn't a pure Perl solution.


1

brainfuck, 21 bytes

-[+>,[<->+[<.>[-]]]<]

Last one, I promise. No input = -1, end of input = 0

How it Works

-[  Enters the loop
  +>, Get input
     [<->+ If not end of input it create the ÿ character and check if the input is not -1
          [<.>[-]]] If there was input, print the ÿ character. 
                    <] Exit the loop if end of input

Your code is missing a closing bracket. And why do you make it that complicated? A simple "print a 'ÿ' for every input character" could be accomplished with a simple ,[>-.,]
Dorian

@Dorian The bracket was a mistake, but the complexity arises from having to handle both no input and end of input
Jo King

0

QBIC, 44 bytes

{X=inkey$~X<>@`|~X=chr$(13)|_X\Y=Y+@*`_C?Y

Explanation

{            DO
X=inkey$     Read a char, set it to X$
             Note that INKEY$ doesn't wait for keypress, but simply sends out "" if no key was pressed.
~X<>@`|      IF X$ has a value THEN
~X=chr$(13)| IF that value is ENTER
_X           THEN END
\            ELSE
Y=Y+@*`      append a literal * to Y$
_C           Clear the screen
?Y           Display Y$ (having 1 * for each char entered)
             The IF's and the DO-loop are auto-closed at EOF{            DO
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.