SlideShare a Scribd company logo
1 of 3
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class encryptFile {
// The crypt() function encrypts or decrypts a byte array input, using
// an 16-byte initialization vector (init), 16-byte password (pass),
// and an integer mode (either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE)
public static byte[] crypt(byte[] input, byte[] init, byte[] pass, int mode) {
// TODO - Fill this out.
}
// The cryptFile() function opens a file at a specified string path,
// then passes in the init, pass, and mode values to the crypt() function
// to either encrypt or decrypt the contents of the file. It then writes
// the encrypted or decrypted data back to the file. Note that it should
// overwrite the existing file - so don't try it on a file that's actually
// worth anything!
public static void cryptFile(String path, byte[] init, byte[] pass, int mode) {
// TODO - Fill this out.
}
// The menu() function provides a user interface for the script. It should
// prompt the user to enter a file path, 16-byte initialization vector,
// 16-byte password, and a mode (encrypt or decrypt). If the password or
// initialization vector are too short or too long, the function should
// re-prompt the user to re-enter the value.
public static void menu() {
// TODO - Fill this out.
}
// Just need to call the menu() function here
public static void main(String[] args) {
// Tests for crypt();
byte[] plain = "Hello World".getBytes();
byte[] pass = "aaaabbbbccccdddd".getBytes();
byte[] init = "gggggggggggggggg".getBytes();
byte[] cipher = crypt(plain, init, pass, Cipher.ENCRYPT_MODE);
byte[] decrypted = crypt(cipher, init, pass, Cipher.DECRYPT_MODE);
// This should print "Hello World"
System.out.println(new String(decrypted));
// Uncomment below to test menu section once complete
//menu();
}
}
than ideal - you generally want to use standardized implementations of cryptographic functions,
as it's much less likely that they'll have internal defects or flaws that pose a security risk. For this
lab, we'll use the javax.crypto libraries in Java. These libraries provide access to a number of
cryptographically-related functions, including the ability to encrypt in AES and DES. A skeleton
file has been provided called encryptFile.java. The crypt() function The first function we'll
complete is the crypt() function. This function takes three byte arrays: an input, which is either a
ciphertext or plaintext, a init, which is a 16 -byte initialization vector (for Chaining Block Mode),
and a pass, which is a 16 -byte key. It also takes a mode, which is an integer. The Cipher module
includes the modes declared as final static integers: Cipher.ENCRYPT_MODE
Cipher.DECRYPT_MODE Inside the function, the first thing we need to do is pass the
initialization vector and the password to the IvParameterSpec and SecretKeySpec objects
respectively. These objects prepare the IV and password for use, and check that they are
appropriate. They must each by 16 bytes in length, no longer and no shorter - this usually equals
16 ASClI characters. The IV byte array can be passed directly into the constructor of a new
IvParameterSpec object: new IvParameterSpec(init); However, when creating a SecretKeySpec
object, you must also specify (in a String) the type of cipher that you are using. In our case, we'll
use AES, and pass in our password byte array object: new SecretKeySpec(pass, "AES"); We can
then create our Cipher object. Rather than use new like we do for most objects, we instead make
a call to the Cipher.getInstance() function, passing in a String that defines several aspects of our
cipher: - The cipher to be used (i.e. AES) - The mode of operation (i.e. CBC (chaining block
cipher) or ECB (electronic code book) - The padding to be used (i.e. PKCS5 standard for
padding) This will create a new Cipher object, which we can then use. Here's an example of what
the getInstance() constructor should look like:
Cipher.getInstance("AES/CBC/PKCSSPADDING"); Then, we need to call the init method on
our new Cipher object. The init method takes three inputs: the integer mode, the SecretKeySpec
object we created, and the IvParameterSpec that we created. Finally, we can perform our
encryption/decryption. We'll take the input byte array and pass it to the dofinal() function of our
initialized Cipher object. This will return a new byte array, which is our output. If we are
performing encryption, the output will be our ciphertext; if we are performing decryption, the
output will be our plaintext. You should then return this bytearray. Note that the above will
require a try/except or a throws declaration around the Cipher-related lines. The cryptFile()
function Now we have a function that can encrypt or decrypt byte arrays at will, so let's put it to
use. The cryptFile() function takes a String path for a file, plus the bytearrays init and pass, and
the integer mode. Inside of the function, we first need to check our file path and create a Path
object. We can do this by just calling the Paths.get() function on our String path; this will return
a new Path object. We can then get a bytearray of the file contents using the Files module, which
has a function Files.readAllBytes(path). Pass in your Path object that you created. This will
return a bytearray of the file contents. Pass the file contents as the input parameter to the crypt
function, along with the init, pass, and mode parameters. This will return the bytearray output
that is either a ciphertext or a plaintext (depending on if you are encrypting or decrypting).
Finally, write the bytearray back to the original file using the Files.write() function. This takes
the Path object and the bytearray as arguments: Files.write(file, output); This function will work
with any type of file, including both plaintext and binary files. You will notice that binary files,
like images, no longer work properly when encrypted. This is because the file header and related
information is encrypted as well, and your computer will be unable to parse what the file is
supposed to be. In order to make it readable again, you just need to decrypt the file using the
same IV and password. You should verify this works by trying to encrypt a text file and an
image. The menu() function Finally, let's put an interface on the script. This is fairly
straightforward and just requires a couple Scanner calls to get user input, along with a couple
loops to catch incorrect-length IV's and passwords. I'll leave this section up to you, but your code
should: - Prompt the user to enter a filepath - Prompt for an initialization vector, and re-prompt if
the user provides an IV that is not exactly 16 bytes in length (use a loop that checks the length()
of the input bytearray). - Do the same as above, but for the password (make sure it's 16 bytes
long) - Prompt the user for either "encrypt" or "decrypt", and then pass in the correct
Cipher_MODE value (as shown earlier in this writeup). Here's an example of what the output
should look like while in use: Enter File Path: src/tux.png Enter Initialization Vector (16 chars):
aaabbbbccccdddd Enter Password ( 16 chars): hello Enter Password ( 16 chars): notlongenough
Enter Password (16 chars): thisis16bytesyes Enter mode: encrypt or decrypt: encrypt Done The
easiest way to do testing for this is to copy files directly into your Eclipse project folder, and then
reference them with a path starting in src. This makes sure that you won't accidentally encrypt
other files on your machine (possibly irreversibly). & sre cosc 232 > caesar.java > D demo.java
> encryptFile.java > MyRandom.java > D sandbox.java > [D stream.java (D) test2.java tux.png
Using DES The crypto library supports many different ciphers and encryption standards,
including the DES and RSA encryption algorithms. Check out the documentation here:
https://docs.oracle.com/iavase/7/docs/api/iavax/crypto/Cipher.html Create a new crypt() function
(name of your choice) that implements an alternate cipher available in the Cipher object, and add
a prompt to your menu() that allows the user to select between AES and the alternate cipher.
When you are done, submit your finished Java file on the course Moodle Page.

More Related Content

Similar to import java-io-IOException- import java-nio-file-Files- import java-ni.docx

Serialization in java
Serialization in javaSerialization in java
Serialization in javaJanu Jahnavi
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18nyifi2009
 
Sour Pickles
Sour PicklesSour Pickles
Sour PicklesSensePost
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfsecunderbadtirumalgi
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingGurpreet singh
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxbudbarber38650
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxbradburgess22840
 

Similar to import java-io-IOException- import java-nio-file-Files- import java-ni.docx (20)

Lecture10
Lecture10Lecture10
Lecture10
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
 
Corba
CorbaCorba
Corba
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18n
 
Java I/O
Java I/OJava I/O
Java I/O
 
Taking User Input in Java
Taking User Input in JavaTaking User Input in Java
Taking User Input in Java
 
Sour Pickles
Sour PicklesSour Pickles
Sour Pickles
 
3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
Biopython
BiopythonBiopython
Biopython
 
Java practical
Java practicalJava practical
Java practical
 
Java adv
Java advJava adv
Java adv
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
 

More from hendriciraida

In a recent annual report and related Global Responsibiity Report- Sta.docx
In a recent annual report and related Global Responsibiity Report- Sta.docxIn a recent annual report and related Global Responsibiity Report- Sta.docx
In a recent annual report and related Global Responsibiity Report- Sta.docxhendriciraida
 
In a nutshell- Social Darwinism is employed by quasi-scientists and po.docx
In a nutshell- Social Darwinism is employed by quasi-scientists and po.docxIn a nutshell- Social Darwinism is employed by quasi-scientists and po.docx
In a nutshell- Social Darwinism is employed by quasi-scientists and po.docxhendriciraida
 
In a modern economy- who controls the creation of money- Who profits f.docx
In a modern economy- who controls the creation of money- Who profits f.docxIn a modern economy- who controls the creation of money- Who profits f.docx
In a modern economy- who controls the creation of money- Who profits f.docxhendriciraida
 
In a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docx
In a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docxIn a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docx
In a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docxhendriciraida
 
In 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docx
In 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docxIn 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docx
In 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docxhendriciraida
 
In 1868- the accidental introduction into the United States of the cot.docx
In 1868- the accidental introduction into the United States of the cot.docxIn 1868- the accidental introduction into the United States of the cot.docx
In 1868- the accidental introduction into the United States of the cot.docxhendriciraida
 
In 1950 the average year of education was 8 years- The standard deviat.docx
In 1950 the average year of education was 8 years- The standard deviat.docxIn 1950 the average year of education was 8 years- The standard deviat.docx
In 1950 the average year of education was 8 years- The standard deviat.docxhendriciraida
 
Important- Python Program- No imports- Use Custom Functions if necessa.docx
Important- Python Program- No imports- Use Custom Functions if necessa.docxImportant- Python Program- No imports- Use Custom Functions if necessa.docx
Important- Python Program- No imports- Use Custom Functions if necessa.docxhendriciraida
 
Impact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docx
Impact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docxImpact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docx
Impact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docxhendriciraida
 
Immune complex is formed when antigen and antibody bind- Formation of.docx
Immune complex is formed when antigen and antibody bind- Formation of.docxImmune complex is formed when antigen and antibody bind- Formation of.docx
Immune complex is formed when antigen and antibody bind- Formation of.docxhendriciraida
 
Imani and Doug were divorced on December 31-2022 - after 10 years of m.docx
Imani and Doug were divorced on December 31-2022 - after 10 years of m.docxImani and Doug were divorced on December 31-2022 - after 10 years of m.docx
Imani and Doug were divorced on December 31-2022 - after 10 years of m.docxhendriciraida
 
Iloginning rav materiala invantoing siding favimaceriala inventory Dif.docx
Iloginning rav materiala invantoing siding favimaceriala inventory Dif.docxIloginning rav materiala invantoing siding favimaceriala inventory Dif.docx
Iloginning rav materiala invantoing siding favimaceriala inventory Dif.docxhendriciraida
 
ii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docx
ii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docxii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docx
ii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docxhendriciraida
 
If you were living in Galveston at the time- how could you have used y.docx
If you were living in Galveston at the time- how could you have used y.docxIf you were living in Galveston at the time- how could you have used y.docx
If you were living in Galveston at the time- how could you have used y.docxhendriciraida
 
If the share price of Nostos- a New York-based shipping firm- rises fr.docx
If the share price of Nostos- a New York-based shipping firm- rises fr.docxIf the share price of Nostos- a New York-based shipping firm- rises fr.docx
If the share price of Nostos- a New York-based shipping firm- rises fr.docxhendriciraida
 
If the mean annual return for common stocks is 11-0- and the standard.docx
If the mean annual return for common stocks is 11-0- and the standard.docxIf the mean annual return for common stocks is 11-0- and the standard.docx
If the mean annual return for common stocks is 11-0- and the standard.docxhendriciraida
 
If NADH donates a pair of electrons to the mitochondrial electron tran.docx
If NADH donates a pair of electrons to the mitochondrial electron tran.docxIf NADH donates a pair of electrons to the mitochondrial electron tran.docx
If NADH donates a pair of electrons to the mitochondrial electron tran.docxhendriciraida
 
If Molly's pension plan from Retirement Management Services included a.docx
If Molly's pension plan from Retirement Management Services included a.docxIf Molly's pension plan from Retirement Management Services included a.docx
If Molly's pension plan from Retirement Management Services included a.docxhendriciraida
 
If a varlable Y supersedes a variable X- then X must be influencing Y.docx
If a varlable Y supersedes a variable X- then X must be influencing Y.docxIf a varlable Y supersedes a variable X- then X must be influencing Y.docx
If a varlable Y supersedes a variable X- then X must be influencing Y.docxhendriciraida
 
If a child is equally likely to be either a boy or girl at birth- and.docx
If a child is equally likely to be either a boy or girl at birth- and.docxIf a child is equally likely to be either a boy or girl at birth- and.docx
If a child is equally likely to be either a boy or girl at birth- and.docxhendriciraida
 

More from hendriciraida (20)

In a recent annual report and related Global Responsibiity Report- Sta.docx
In a recent annual report and related Global Responsibiity Report- Sta.docxIn a recent annual report and related Global Responsibiity Report- Sta.docx
In a recent annual report and related Global Responsibiity Report- Sta.docx
 
In a nutshell- Social Darwinism is employed by quasi-scientists and po.docx
In a nutshell- Social Darwinism is employed by quasi-scientists and po.docxIn a nutshell- Social Darwinism is employed by quasi-scientists and po.docx
In a nutshell- Social Darwinism is employed by quasi-scientists and po.docx
 
In a modern economy- who controls the creation of money- Who profits f.docx
In a modern economy- who controls the creation of money- Who profits f.docxIn a modern economy- who controls the creation of money- Who profits f.docx
In a modern economy- who controls the creation of money- Who profits f.docx
 
In a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docx
In a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docxIn a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docx
In a 1-1-5 page document (APA format- 12-point font- double-spaced) an.docx
 
In 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docx
In 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docxIn 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docx
In 2017 in the economy of Cortania- Consumption was $1500-00- Investme.docx
 
In 1868- the accidental introduction into the United States of the cot.docx
In 1868- the accidental introduction into the United States of the cot.docxIn 1868- the accidental introduction into the United States of the cot.docx
In 1868- the accidental introduction into the United States of the cot.docx
 
In 1950 the average year of education was 8 years- The standard deviat.docx
In 1950 the average year of education was 8 years- The standard deviat.docxIn 1950 the average year of education was 8 years- The standard deviat.docx
In 1950 the average year of education was 8 years- The standard deviat.docx
 
Important- Python Program- No imports- Use Custom Functions if necessa.docx
Important- Python Program- No imports- Use Custom Functions if necessa.docxImportant- Python Program- No imports- Use Custom Functions if necessa.docx
Important- Python Program- No imports- Use Custom Functions if necessa.docx
 
Impact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docx
Impact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docxImpact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docx
Impact on Taxes- You have a marginal tax rate of 22-- You suddenly rea.docx
 
Immune complex is formed when antigen and antibody bind- Formation of.docx
Immune complex is formed when antigen and antibody bind- Formation of.docxImmune complex is formed when antigen and antibody bind- Formation of.docx
Immune complex is formed when antigen and antibody bind- Formation of.docx
 
Imani and Doug were divorced on December 31-2022 - after 10 years of m.docx
Imani and Doug were divorced on December 31-2022 - after 10 years of m.docxImani and Doug were divorced on December 31-2022 - after 10 years of m.docx
Imani and Doug were divorced on December 31-2022 - after 10 years of m.docx
 
Iloginning rav materiala invantoing siding favimaceriala inventory Dif.docx
Iloginning rav materiala invantoing siding favimaceriala inventory Dif.docxIloginning rav materiala invantoing siding favimaceriala inventory Dif.docx
Iloginning rav materiala invantoing siding favimaceriala inventory Dif.docx
 
ii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docx
ii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docxii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docx
ii) the 16000$ restumping fee iii- Ihe $2000 tor the new hot water sys.docx
 
If you were living in Galveston at the time- how could you have used y.docx
If you were living in Galveston at the time- how could you have used y.docxIf you were living in Galveston at the time- how could you have used y.docx
If you were living in Galveston at the time- how could you have used y.docx
 
If the share price of Nostos- a New York-based shipping firm- rises fr.docx
If the share price of Nostos- a New York-based shipping firm- rises fr.docxIf the share price of Nostos- a New York-based shipping firm- rises fr.docx
If the share price of Nostos- a New York-based shipping firm- rises fr.docx
 
If the mean annual return for common stocks is 11-0- and the standard.docx
If the mean annual return for common stocks is 11-0- and the standard.docxIf the mean annual return for common stocks is 11-0- and the standard.docx
If the mean annual return for common stocks is 11-0- and the standard.docx
 
If NADH donates a pair of electrons to the mitochondrial electron tran.docx
If NADH donates a pair of electrons to the mitochondrial electron tran.docxIf NADH donates a pair of electrons to the mitochondrial electron tran.docx
If NADH donates a pair of electrons to the mitochondrial electron tran.docx
 
If Molly's pension plan from Retirement Management Services included a.docx
If Molly's pension plan from Retirement Management Services included a.docxIf Molly's pension plan from Retirement Management Services included a.docx
If Molly's pension plan from Retirement Management Services included a.docx
 
If a varlable Y supersedes a variable X- then X must be influencing Y.docx
If a varlable Y supersedes a variable X- then X must be influencing Y.docxIf a varlable Y supersedes a variable X- then X must be influencing Y.docx
If a varlable Y supersedes a variable X- then X must be influencing Y.docx
 
If a child is equally likely to be either a boy or girl at birth- and.docx
If a child is equally likely to be either a boy or girl at birth- and.docxIf a child is equally likely to be either a boy or girl at birth- and.docx
If a child is equally likely to be either a boy or girl at birth- and.docx
 

Recently uploaded

Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint23600690
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaEADTU
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 

Recently uploaded (20)

Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 

import java-io-IOException- import java-nio-file-Files- import java-ni.docx

  • 1. import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class encryptFile { // The crypt() function encrypts or decrypts a byte array input, using // an 16-byte initialization vector (init), 16-byte password (pass), // and an integer mode (either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE) public static byte[] crypt(byte[] input, byte[] init, byte[] pass, int mode) { // TODO - Fill this out. } // The cryptFile() function opens a file at a specified string path, // then passes in the init, pass, and mode values to the crypt() function // to either encrypt or decrypt the contents of the file. It then writes // the encrypted or decrypted data back to the file. Note that it should // overwrite the existing file - so don't try it on a file that's actually // worth anything! public static void cryptFile(String path, byte[] init, byte[] pass, int mode) { // TODO - Fill this out. } // The menu() function provides a user interface for the script. It should // prompt the user to enter a file path, 16-byte initialization vector, // 16-byte password, and a mode (encrypt or decrypt). If the password or // initialization vector are too short or too long, the function should // re-prompt the user to re-enter the value. public static void menu() { // TODO - Fill this out. } // Just need to call the menu() function here public static void main(String[] args) { // Tests for crypt(); byte[] plain = "Hello World".getBytes(); byte[] pass = "aaaabbbbccccdddd".getBytes(); byte[] init = "gggggggggggggggg".getBytes(); byte[] cipher = crypt(plain, init, pass, Cipher.ENCRYPT_MODE); byte[] decrypted = crypt(cipher, init, pass, Cipher.DECRYPT_MODE);
  • 2. // This should print "Hello World" System.out.println(new String(decrypted)); // Uncomment below to test menu section once complete //menu(); } } than ideal - you generally want to use standardized implementations of cryptographic functions, as it's much less likely that they'll have internal defects or flaws that pose a security risk. For this lab, we'll use the javax.crypto libraries in Java. These libraries provide access to a number of cryptographically-related functions, including the ability to encrypt in AES and DES. A skeleton file has been provided called encryptFile.java. The crypt() function The first function we'll complete is the crypt() function. This function takes three byte arrays: an input, which is either a ciphertext or plaintext, a init, which is a 16 -byte initialization vector (for Chaining Block Mode), and a pass, which is a 16 -byte key. It also takes a mode, which is an integer. The Cipher module includes the modes declared as final static integers: Cipher.ENCRYPT_MODE Cipher.DECRYPT_MODE Inside the function, the first thing we need to do is pass the initialization vector and the password to the IvParameterSpec and SecretKeySpec objects respectively. These objects prepare the IV and password for use, and check that they are appropriate. They must each by 16 bytes in length, no longer and no shorter - this usually equals 16 ASClI characters. The IV byte array can be passed directly into the constructor of a new IvParameterSpec object: new IvParameterSpec(init); However, when creating a SecretKeySpec object, you must also specify (in a String) the type of cipher that you are using. In our case, we'll use AES, and pass in our password byte array object: new SecretKeySpec(pass, "AES"); We can then create our Cipher object. Rather than use new like we do for most objects, we instead make a call to the Cipher.getInstance() function, passing in a String that defines several aspects of our cipher: - The cipher to be used (i.e. AES) - The mode of operation (i.e. CBC (chaining block cipher) or ECB (electronic code book) - The padding to be used (i.e. PKCS5 standard for padding) This will create a new Cipher object, which we can then use. Here's an example of what the getInstance() constructor should look like: Cipher.getInstance("AES/CBC/PKCSSPADDING"); Then, we need to call the init method on our new Cipher object. The init method takes three inputs: the integer mode, the SecretKeySpec object we created, and the IvParameterSpec that we created. Finally, we can perform our encryption/decryption. We'll take the input byte array and pass it to the dofinal() function of our initialized Cipher object. This will return a new byte array, which is our output. If we are performing encryption, the output will be our ciphertext; if we are performing decryption, the output will be our plaintext. You should then return this bytearray. Note that the above will require a try/except or a throws declaration around the Cipher-related lines. The cryptFile() function Now we have a function that can encrypt or decrypt byte arrays at will, so let's put it to use. The cryptFile() function takes a String path for a file, plus the bytearrays init and pass, and the integer mode. Inside of the function, we first need to check our file path and create a Path object. We can do this by just calling the Paths.get() function on our String path; this will return a new Path object. We can then get a bytearray of the file contents using the Files module, which has a function Files.readAllBytes(path). Pass in your Path object that you created. This will
  • 3. return a bytearray of the file contents. Pass the file contents as the input parameter to the crypt function, along with the init, pass, and mode parameters. This will return the bytearray output that is either a ciphertext or a plaintext (depending on if you are encrypting or decrypting). Finally, write the bytearray back to the original file using the Files.write() function. This takes the Path object and the bytearray as arguments: Files.write(file, output); This function will work with any type of file, including both plaintext and binary files. You will notice that binary files, like images, no longer work properly when encrypted. This is because the file header and related information is encrypted as well, and your computer will be unable to parse what the file is supposed to be. In order to make it readable again, you just need to decrypt the file using the same IV and password. You should verify this works by trying to encrypt a text file and an image. The menu() function Finally, let's put an interface on the script. This is fairly straightforward and just requires a couple Scanner calls to get user input, along with a couple loops to catch incorrect-length IV's and passwords. I'll leave this section up to you, but your code should: - Prompt the user to enter a filepath - Prompt for an initialization vector, and re-prompt if the user provides an IV that is not exactly 16 bytes in length (use a loop that checks the length() of the input bytearray). - Do the same as above, but for the password (make sure it's 16 bytes long) - Prompt the user for either "encrypt" or "decrypt", and then pass in the correct Cipher_MODE value (as shown earlier in this writeup). Here's an example of what the output should look like while in use: Enter File Path: src/tux.png Enter Initialization Vector (16 chars): aaabbbbccccdddd Enter Password ( 16 chars): hello Enter Password ( 16 chars): notlongenough Enter Password (16 chars): thisis16bytesyes Enter mode: encrypt or decrypt: encrypt Done The easiest way to do testing for this is to copy files directly into your Eclipse project folder, and then reference them with a path starting in src. This makes sure that you won't accidentally encrypt other files on your machine (possibly irreversibly). & sre cosc 232 > caesar.java > D demo.java > encryptFile.java > MyRandom.java > D sandbox.java > [D stream.java (D) test2.java tux.png Using DES The crypto library supports many different ciphers and encryption standards, including the DES and RSA encryption algorithms. Check out the documentation here: https://docs.oracle.com/iavase/7/docs/api/iavax/crypto/Cipher.html Create a new crypt() function (name of your choice) that implements an alternate cipher available in the Cipher object, and add a prompt to your menu() that allows the user to select between AES and the alternate cipher. When you are done, submit your finished Java file on the course Moodle Page.