import java.io.FilePermission;
import java.io.*;
import java.security.*;

public class TestSecurity  {
  public static void main(String[] args) throws IOException, FileNotFoundException, NoSuchAlgorithmException {
    /* Demo 1 ~ Check permission to read policy file.
          Attempt to read an application text file.
    */
    SecurityManager sm = System.getSecurityManager();
    try {
      sm.checkPermission(new FilePermission("../security-file-location/java.policy", "read"));
    } catch (Exception ex) {
      System.out.println("Exception detected: " + ex.getMessage());
    }
    
    BufferedReader br = new BufferedReader(new FileReader("../security-file-location/security.txt"));
    System.out.println(br.readLine());
    
    /* Demo 2 ~ Hash a password using SHA-256 and store the password
          Prompt user for the password and then compare the hashed user password with the password stored
    */
    // Hash password using SHA (Secure Hashing Algorithm) 256
    MessageDigest sha = MessageDigest.getInstance("SHA-256");
    String passwordToHash = "java";
    byte[] bytes = passwordToHash.getBytes();
    byte[] hashedPassword = sha.digest(bytes);
    StringBuilder hashedPasswordSB = new StringBuilder("");
    // Create StringBuilder object to store hashed password
    for (byte b : hashedPassword) {
      hashedPasswordSB.append(b);
      System.out.print(b);
    }
    
    // Prompt user for password, hash the password and compare with the stored password
    BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("\nEnter password: ");
    String pw = br2.readLine();
    byte[] userBytes = pw.getBytes();
    byte[] hashedUserPassword = sha.digest(userBytes);
    
    StringBuilder hashedUserPasswordSB = new StringBuilder("");
    // Create StringBuilder object to store user password
    for (byte b : hashedUserPassword) {
      hashedUserPasswordSB.append(b);
      System.out.print(b);
    }
    
    if (hashedUserPasswordSB.toString().equals(hashedPasswordSB.toString())) {
      System.out.println("\nLogin succeeded");
    } 
    else {
      System.out.println("\nLogin failed");
    }
  }
}