totpgenerator

TOTP code generator
git clone git://git.wimdupont.com/totpgenerator.git
Log | Files | Refs | README | LICENSE

KeyRetriever.java (1797B)


      1 package com.wimdupont.service;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileNotFoundException;
      6 import java.io.IOException;
      7 import java.io.InputStream;
      8 import java.util.Arrays;
      9 import java.util.Scanner;
     10 import java.util.stream.Collectors;
     11 
     12 public class KeyRetriever {
     13 
     14     private static final String GPG_EXTENSION = ".gpg";
     15 
     16     public static InputStream getSecretKeyInputStream(String fileArgument,
     17                                                       String dirPath) throws IOException {
     18         var scanner = new Scanner(System.in);
     19         File file;
     20 
     21         if (fileArgument != null) {
     22             file = new File(dirPath + fileArgument + GPG_EXTENSION).getAbsoluteFile();
     23             if (!file.exists()) {
     24                 throw new FileNotFoundException(String.format("File \"%s\" not found", file.getName()));
     25             }
     26         } else {
     27             var files = new File(dirPath).listFiles();
     28             if (files == null || files.length < 1) {
     29                 throw new FileNotFoundException(dirPath + " contains no files");
     30             }
     31             String fileNames = Arrays.stream(files)
     32                     .filter(f -> f.getName().contains(GPG_EXTENSION))
     33                     .map(f -> f.getName().replace(GPG_EXTENSION, ""))
     34                     .collect(Collectors.joining(", "));
     35 
     36             System.out.println("Which TOTP?");
     37             System.out.println(fileNames);
     38 
     39             String fileName = scanner.nextLine();
     40 
     41             file = Arrays.stream(files)
     42                     .filter(f -> f.getName().replace(GPG_EXTENSION, "").equals(fileName))
     43                     .findAny()
     44                     .orElseThrow(() -> new FileNotFoundException("File not found"));
     45         }
     46 
     47         return new FileInputStream(file.getAbsolutePath());
     48     }
     49 }