Browse Source

Added comments

master
school 7 years ago
parent
commit
a326703475
  1. 33
      AESEncryption.java

33
AESEncryption.java

@ -11,7 +11,6 @@ public class AESEncryption
Scanner input = new Scanner(System.in);
System.out.print("Enter E for encyrption or D for decryption: ");
String a = input.nextLine();
if(a.equals("E"))
{
encrypt();
@ -23,35 +22,43 @@ public class AESEncryption
}
public static void encrypt()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = input.nextLine();
File file = new File(fileName);
try
{
// create secret key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey key = keyGen.generateKey();
// initialize aes encryption object
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
// read in bytes
FileInputStream fis = new FileInputStream(file);
byte[] byteArray = new byte[(int)file.length()];
int buffer = fis.read(byteArray);
// encrypt bytes
byte[] bArray = cipher.doFinal(byteArray);
// write bytes (in place)
FileOutputStream fos = new FileOutputStream(file);
fos.write(bArray);
// write key to file
FileOutputStream encodedKey = new FileOutputStream("key.txt");
byte[] keys = key.getEncoded();
encodedKey.write(keys);
// close result file
fis.close();
fos.close();
// close key file
encodedKey.close();
}
catch(FileNotFoundException fnfe)
@ -82,46 +89,43 @@ public class AESEncryption
{
System.out.println("the given key is inappropriate for initializing this cipher");
}
}//end of encrypt method
}
public static void decrypt()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name of whats to be decrypted: ");
String fileName = input.nextLine();
System.out.print("Enter the file name of the key: ");
String keyName = input.nextLine();
File encryptedFile = new File(fileName);
File encryptedKey = new File(keyName);
try
{
// load all data
FileInputStream fisKey = new FileInputStream(encryptedKey);
FileInputStream fisFile = new FileInputStream(encryptedFile);
FileOutputStream fos = new FileOutputStream("decryptedFile.txt");
// initialize output byte array
byte[] fileArray = new byte[(int)encryptedFile.length()];
int buffer2 = fisFile.read(fileArray);
// initialize key byte array
byte[] keyBytes = new byte[(int)encryptedKey.length()];
int buffer = fisKey.read(keyBytes);
// construct secret key from key bytes
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
// initialize cipher and decrypt
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] cipherBytes = cipher.doFinal(fileArray);
// write to file
fos.write(cipherBytes);
fisKey.close();
fos.close();
fisFile.close();
}
catch(FileNotFoundException fnfe)
{
@ -155,6 +159,5 @@ public class AESEncryption
{
System.out.println("bad or invalid padding/block");
}
}
}
}
Loading…
Cancel
Save