]>
code.octet-stream.net Git - hashgood/blob - src/main.rs
2f1e7f321c7328e6e0772b0392f4b1d3b384d28e
2 use std
::path
::PathBuf
;
4 use structopt
::StructOpt
;
6 /// Calculate digests for given input data
9 /// Display output nicely in the terminal
12 /// Collect candidate hashes based on options and match them against a calculated hash
16 #[structopt(name = "hashgood")]
18 /// Read the hash from the clipboard
19 #[structopt(short = "p", long = "paste")]
22 /// Disable ANSI colours in output
23 #[structopt(short = "C", long = "no-colour")]
26 /// A file containing the hash to verify. It can either be a raw hash or a SHASUMS-style listing. Use `-` for standard input.
27 #[structopt(short = "c", long = "check", parse(from_os_str))]
28 hash_file
: Option
<PathBuf
>,
30 /// The file to be verified or `-` for standard input
31 #[structopt(name = "input", parse(from_os_str))]
34 /// A hash to verify, supplied directly on the command line
35 #[structopt(name = "hash")]
39 /// Types of supported digest algorithm
40 #[derive(Debug, PartialEq, Copy, Clone)]
48 /// Assume a hash type from the binary length. Fortunately the typical 3 algorithms we care about are different lengths.
49 pub fn from_len(len
: usize) -> Result
<Algorithm
, String
> {
51 16 => Ok(Algorithm
::Md5
),
52 20 => Ok(Algorithm
::Sha1
),
53 32 => Ok(Algorithm
::Sha256
),
54 _
=> Err(format
!("Unrecognised hash length: {} bytes", len
)),
59 /// The method by which one or more hashes were supplied to verify the calculated digest
60 pub enum VerificationSource
{
67 /// A complete standalone hash result
75 pub fn new(alg
: Algorithm
, bytes
: Vec
<u8>, path
: &PathBuf
) -> Self {
76 // Taking the filename component should always work?
77 // If not, just fall back to the full path
78 let filename
= match path
.file
_name
() {
79 Some(filename
) => filename
.to_string_lossy(),
80 None
=> path
.to_string_lossy(),
85 filename
: filename
.to_string(),
90 /// A possible hash to match against. The algorithm is assumed.
91 pub struct CandidateHash
{
93 filename
: Option
<String
>,
96 /// A list of candidate hashes that our input could potentially match. At this point it is
97 /// assumed that we will be verifying a digest of a particular, single algorithm.
98 pub struct CandidateHashes
{
100 hashes
: Vec
<CandidateHash
>,
101 source
: VerificationSource
,
104 /// Summary of an atetmpt to match the calculated digest against candidates
105 pub enum MatchLevel
{
111 /// The severity of any informational messages to be printed before the final result
112 pub enum MessageLevel
{
118 /// Overall details of an attempt to match the calculated digest against candidates
119 pub struct Verification
<'a
> {
120 match_level
: MatchLevel
,
121 comparison_hash
: Option
<&'a CandidateHash
>,
122 messages
: Vec
<(MessageLevel
, String
)>,
125 /// Entry point - run the program and handle errors ourselves cleanly.
127 /// At the moment there aren't really any errors that can be handled by the application. Therefore
128 /// stringly-typed errors are used and they are all captured here, where the problem is printed
129 /// and the application terminates with a non-zero return code.
131 hashgood().unwrap
_or
_else
(|e
| {
132 eprintln
!("Error: {}", e
);
137 /// Main application logic
138 fn hashgood() -> Result
<(), Box
<dyn Error
>> {
139 let opt
= get_verified_options()?
;
140 let candidates
= verify
::get_candidate_hashes(&opt
)?
;
141 let input
= calculate
::get_input_reader(&opt
.inp
ut
)?
;
142 if let Some(c
) = candidates
{
143 // If we have a candidate hash of a particular type, use that specific algorithm
144 let hashes
= calculate
::create_digests(&[c
.alg
], input
)?
;
145 for (alg
, bytes
) in hashes
{
146 // Should always be true
148 let hash
= Hash
::new(alg
, bytes
, &opt
.inp
ut
);
149 let verification
= verify
::verify_hash(&hash
, &c
);
152 verification
.comparison_hash
,
156 display
::print_messages(verification
.messages
, opt
.no_colour
)?
;
157 display
::print_match_level(verification
.match_level
, opt
.no_colour
)?
;
161 // If no candidate, calculate all three common digest types for output
162 let hashes
= calculate
::create_digests(
163 &[Algorithm
::Md5
, Algorithm
::Sha1
, Algorithm
::Sha256
],
166 for (alg
, bytes
) in hashes
{
170 filename
: opt
.inp
ut
.file
_name
().unwrap
().to_string_lossy().to_string(),
172 display
::print_hash(&hash
, None
, None
, opt
.no_colour
)?
;
178 /// Parse the command line options and check for ambiguous or inconsistent settings
179 fn get_verified_options() -> Result
<Opt
, String
> {
180 let opt
= Opt
::from_args();
182 opt
.hash
.is
_some
() as i32 + opt
.paste
as i32 + opt
.hash_file
.is
_some
() as i32;
183 if hash_methods
> 1 {
184 if opt
.hash
.is
_some
() {
185 eprintln
!("* specified as command line argument");
188 eprintln
!("* paste from clipboard (-p)")
190 if opt
.hash_file
.is
_some
() {
191 eprintln
!("* check hash from file (-c)")
193 return Err("Error: Hashes were provided by multiple methods. Use only one.".to_owned());
195 if opt
.inp
ut
.to_str() == Some("-")
196 && opt
.hash_file
.as_ref().and_then(|h
| h
.to_str()) == Some("-")
198 return Err("Error: Cannot use use stdin for both hash file and input data".to_owned());