Skip to content

Instantly share code, notes, and snippets.

@iamfeek
Created October 23, 2020 17:14
Show Gist options
  • Save iamfeek/f4607c802d27b9aa2f421a911af3d3ab to your computer and use it in GitHub Desktop.
Save iamfeek/f4607c802d27b9aa2f421a911af3d3ab to your computer and use it in GitHub Desktop.
Joash's School Assignment
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
class InvalidPasswordException extends Exception {
int passwordConditionViolated = 0;
public InvalidPasswordException(int conditionViolated)
{
super("Invalid Password: ");
passwordConditionViolated = conditionViolated;
}
public String printMessage()
{
// Call constructor of parent Exception
// according to the condition violated
switch (passwordConditionViolated) {
// Password length should be
// between 8 to 15 characters
case 1:
return ("Password length should be between 8 to 15 characters");
// Password should not contain any space
case 2:
return ("Password should not contain any space");
// Password should contain// at least one digit(0-9)
case 3:
return ("Password should contain at least one digit(0-9)");
// Password should contain at least
// one special character ( @, #, %, &, !, $ )
case 4:
return ("Password should contain at least one special character");
// Password should contain at least
// one uppercase letter(A-Z)
case 5:
return ("Password should contain at least one uppercase letter(A-Z)");
// Password should contain at least
// one lowercase letter(a-z)
case 6:
return ("Password should contain at least one lowercase letter(a-z)");
}
return ("");
}
}
public class Assignment1 {
public static void isValid(String password) throws InvalidPasswordException
{
// for checking if password length
// is between 8 and 15
if (!((password.length() >= 8)
&& (password.length() <= 16))) {
throw new InvalidPasswordException(1);
}
// to check space
if (password.contains(" ")) {
throw new InvalidPasswordException(2);
}
if (true) {
int count = 0;
// check digits from 0 to 9
for (int i = 0; i <= 9; i++) {
// to convert int to string
String str1 = Integer.toString(i);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
throw new InvalidPasswordException(3);
}
}
// for special characters
if (!(password.contains("@") || password.contains("#")
|| password.contains("!") || password.contains("~")
|| password.contains("$") || password.contains("%")
|| password.contains("^") || password.contains("&")
|| password.contains("*") || password.contains("(")
|| password.contains(")") || password.contains("-")
|| password.contains("+") || password.contains("/")
|| password.contains(":") || password.contains(".")
|| password.contains(", ") || password.contains("<")
|| password.contains(">") || password.contains("?")
|| password.contains("|"))) {
throw new InvalidPasswordException(4);
}
if (true) {
int count = 0;
// checking capital letters
for (int i = 65; i <= 90; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
throw new InvalidPasswordException(5);
}
}
if (true) {
int count = 0;
// checking small letters
for (int i = 90; i <= 122; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
throw new InvalidPasswordException(6);
}
}
// The password is valid
}
public static String getMd5(String input) {
try {
// Static getInstance method is called with hashing MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// digest() method is called to calculate message digest
// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static void createTxt() throws IOException {
// create salt.txt
File slt = new File("salt.txt");
slt.createNewFile(); // if file already exists will do nothing
// FileOutputStream oFile = new FileOutputStream(myFile, false);
// fileCreate();
//create shadow.txt
File shadow = new File("shadow.txt");
shadow.createNewFile();
File fs = new File("file.store.txt");
fs.createNewFile();
}
public static void createUser()throws IOException, InvalidPasswordException {
File slt = new File("salt.txt");
File shadow = new File("shadow.txt");
Scanner myObj = new Scanner(System.in);
Scanner salt = new Scanner(slt);
Scanner shad = new Scanner(shadow);
FileWriter saltfw = new FileWriter("salt.txt", true);
BufferedWriter saltbw = new BufferedWriter(saltfw);
FileWriter shadfw = new FileWriter("shadow.txt", true);
BufferedWriter shadbw = new BufferedWriter(shadfw);
System.out.print("Enter Username: ");
String userName = myObj.nextLine();
while (salt.hasNextLine()) {
String[] data = salt.nextLine().split(":");
// System.out.println(salt.nextLine());
if (data[0].equals(userName)) {
System.out.println("User already exist");
System.exit(0);
}
}
Console console = System.console();
int pwCheck = 0;
String pw1 = "";
String pw2 = "";
while (pwCheck < 4){
System.out.print("Enter Password: ");
pw1 = myObj.nextLine();
// console.printf("Enter Password: ");
// char [] password1 = console.readPassword();
// pw1 = new String(password1);
try {
isValid(pw1);
System.out.print("Confirm Password: ");
pw2 = myObj.nextLine();
//console.printf("Confirm Password: ");
// char [] password2 = console.readPassword();
// pw2 = new String(password2);
if (pw1.equals(pw2)) {
// System.out.print("GTFO.\n");
break;
}
else {
System.out.print("Password does not match.\n");
pwCheck++;
// System.out.println(pwCheck);
}
}
catch (InvalidPasswordException e) {
System.out.print(e.getMessage());
System.out.println(e.printMessage());
pwCheck++;
// System.out.println(pwCheck);
}
if (pwCheck==4){
System.exit(0);}
}
System.out.print("Enter clearance level: ");
String CL = myObj.nextLine();
if (!CL.equals("0") & !CL.equals("1") & !CL.equals("2") & !CL.equals("3")){
System.out.println("Invalid clearance level.");
System.exit(0);
}
String NUM = "0123456789";
StringBuilder sb = new StringBuilder();
for (int i=0; i<8; i++){
int index = (int)(NUM.length() * Math.random());
sb.append(NUM.charAt(index));
}
// System.out.println(pw1+sb);
// System.out.println(getMd5(pw1+sb));
saltbw.append(userName + ":"+ sb +"\n");
shadbw.append(userName + ":"+getMd5(pw1+sb)+":"+CL+"\n");
System.out.println("Successfully wrote to the file.");
//bw.append(userName + ":"+ pw1 + ":" +CL+"\n");
saltbw.flush();
saltbw.close();
shadbw.flush();
shadbw.close();
// bw.append(userName + "\n");
// bw.flush();
// bw.close();
// System.out.println("Successfully wrote to the file.");
}
public static String[] Login() throws IOException {
File slt = new File("salt.txt");
File shadow = new File("shadow.txt");
Scanner myObj = new Scanner(System.in);
Scanner salt = new Scanner(slt);
Scanner shad = new Scanner(shadow);
System.out.print("Enter Username: ");
String UsrNm = myObj.nextLine();
String pwdSalt= "";
String shadpwdHash = "";
String shadCL = "";
boolean userFound = false;
while (salt.hasNextLine()) {
String[] data = salt.nextLine().split(":");
// System.out.println(salt.nextLine());
if (data[0].equals(UsrNm)) {
// System.out.println("fk");
// System.out.println(data[1]);
userFound = true;
pwdSalt= data[1];
break;
}
}
while (shad.hasNextLine()) {
String[] data = shad.nextLine().split(":");
// System.out.println(salt.nextLine());
if (data[0].equals(UsrNm)) {
// System.out.println("fk");
// System.out.println(data[1]);
shadpwdHash= data[1];
shadCL = data[2];
break;
}
}
if (!userFound ){
System.out.println("Invalid Username");
System.exit(0);
}
//Console console = System.console();
//console.printf("Enter Password: ");
// char [] password1 = console.readPassword();
// pwd = new String(password1);
System.out.print("Enter Password: ");
String pwd = myObj.nextLine();
String pwdHash = getMd5(pwd+pwdSalt);
System.out.println(UsrNm + " found in salt.txt");
System.out.println("salt retrieved: " + pwdSalt);
System.out.println("hashing...");
System.out.println("hash value: " + pwdHash);
if(pwdHash.equals(shadpwdHash)) {
System.out.println("Authentication for user "+ UsrNm + " complete.");
System.out.println("The clearance for "+ UsrNm + " is "+ shadCL +"\n");
}
else{
System.out.println("Incorrect Password.");
System.exit(0);
}
//System.out.println(pwdSalt + "fk mi life");
// loggedIn(UsrNm, shadCL);
return new String[]{UsrNm,shadCL};
}
// public static String[] usrName(String Name, String clearance){
// String usrName = Name;
// String CL = clearance;
// return new String[]{usrName, CL};
// }
public static int showMenuNGetOption(
String username,
String clearanceLevel,
String filename
) throws IOException {
Scanner scanner = new Scanner(System.in);
File fileStore = new File("file.store.txt");
Scanner sf = new Scanner(fileStore);
FileWriter FWfileStore = new FileWriter("file.store.txt", true);
BufferedWriter BWfileStore = new BufferedWriter(FWfileStore);
String usrInput= "";
while(!usrInput.equalsIgnoreCase("C") & !usrInput.equalsIgnoreCase("A")& !usrInput.equalsIgnoreCase("R")& !usrInput.equalsIgnoreCase("W")& !usrInput.equalsIgnoreCase("L")& !usrInput.equalsIgnoreCase("S")& !usrInput.equalsIgnoreCase("E") ) {
System.out.println("Options: (C)reate, (A)ppend, (R)ead, (W)rite, (L)ist, (S)ave or (E)xit");
usrInput = scanner.nextLine();
if (usrInput.equalsIgnoreCase("C")) {
System.out.println("Enter Filename: ");
filename = scanner.nextLine();
File usrFile = new File(filename);
usrFile.createNewFile();
System.out.println("File Created");
showMenuNGetOption(username, clearanceLevel, filename);
}
else if (usrInput.equalsIgnoreCase("A")) {
System.out.println("APPEND");
break;
}
else if (usrInput.equalsIgnoreCase("R")) {
System.out.println("READ");
break;
}
else if (usrInput.equalsIgnoreCase("W")) {
System.out.println("WRITE");
break;
}
else if (usrInput.equalsIgnoreCase("L")) {
// System.out.println("List ");
String line;
while (sf.hasNextLine()) {
System.out.println(sf.nextLine());
}
showMenuNGetOption(username, clearanceLevel, filename);
}
else if (usrInput.equalsIgnoreCase("S")) {
BWfileStore.append(filename+":"+username+":"+clearanceLevel);
BWfileStore.flush();
BWfileStore.close();
System.out.println("File Save");
System.out.println(filename);
showMenuNGetOption(username, clearanceLevel, filename);
}
else if (usrInput.equalsIgnoreCase("E")) {
System.out.println("Shut down the FileSystem? (Y)es or (N)o ");
String sd = scanner.nextLine();
if (sd.equalsIgnoreCase("y")){
break;}
else{
showMenuNGetOption(username, clearanceLevel, filename);
}
}
}
return 0;
}
public static void main(String[] args) throws IOException, InvalidPasswordException {
createTxt();
// createUser();
String[] userCredentials = Login();
String username = userCredentials[0];
String clearanceLevel = userCredentials[1];
showMenuNGetOption(username, clearanceLevel, "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment