#!/usr/bin/env perl

use strict;
use warnings;
use Digest::SHA qw(sha1_hex);

# Script to check a password via pwnedpasswords.com with k-anonimity
# https://www.troyhunt.com/ive-just-launched-pwned-passwords-version-2/#cloudflareprivacyandkanonymity
# https://haveibeenpwned.com/API/v2#PwnedPasswords

my $api = "https://api.pwnedpasswords.com/range/";

my $curlBin = `which curl`;
chomp $curlBin;

if ( ! -f $curlBin ) {
print "You need curl to use this script\n";
exit 1;
}

if ( ! defined $ARGV[0] ) {
print "Please pass a password\n";
exit 1;
}

# Clear term to remove visible pw from screen
my $clear_bin = `which clear`;
chomp $clear_bin;
if ( -f $clear_bin ) {
#system("$clear_bin");
}

my $pw = shift(@ARGV);
chomp $pw;
my $pw_sha1 = uc(sha1_hex("$pw"));
$pw_sha1 =~ m/(^[0-9A-Z]{40})/;
$pw_sha1 = $1;
$pw_sha1 =~ m/(^[0-9A-Z]{5})([0-9A-Z]{35})/;
my $first_five = $1;
my $rest = $2;
chomp $first_five; chomp $rest;

my @results = split("\n", `curl -s $api/$first_five`);
my $count = 0;
foreach my $result ( @results ) {
chomp $result;
$result =~ m/(^[0-9A-Z]{35})/;
my $segment = $1;
if ( $segment eq $rest ) {
$result =~ m/^([0-9A-Z]{35})\:([0-9].*)$/;
my $count = $2;
$count =~ s/\r//g;
print "$count appearances\n";
exit 0;
} else {
next;
}
}

print "No appearances\n";