This example uses AES (Advanced Encryption Standard) to encrypt a file. To use the modifier to generate the key first,
Run the following command: Java aestest-genkey Secret.key so the key is saved to the Secret.key file.
You can now encrypt the file with the following command: Java aestest-encrypt F:\javacode\a.html F:\javacode\x.html Secret.key.
The first is to get the key in Secret.key and then read the a.html to put the contents of it encrypted into x.html.
Decrypt the following command: Java aestest-decrypt F:\javacode\x.html F:\javacode\b.html Secret.key.
In the same way, Secret.key gets the key and then decrypts the contents of the encrypted x.html file and places the decrypted content in the b.html.
So the content in the a.html is the same as the content in b.html.
Import java.io.*;
Import java.security.*;
Import javax.crypto.*; /** * This program tests the AES cipher.
Usage:<br> * java aestest-genkey keyfile<br> * java aestest-encrypt plaintext encrypted keyfile<br> * Java Aestest-decrypt encrypted decrypted keyfile<br> * @author Cay Horstmann * @version 1.0 2004-09-14/Pub Lic class Aestest {public static void main (string[] args) {try {if args[0].equals ("-genkey"
) {Keygenerator keygen = keygenerator.getinstance ("AES");
SecureRandom random = new SecureRandom ();
Keygen.init (random);
Secretkey key = Keygen.generatekey ();
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream (args[1));
Out.writeobject (key);
Out.close ();
else {int mode;
if (Args[0].equals ("-encrypt")) mode = Cipher.encrypt_mode; else mode = CipHer.
Decrypt_mode;
ObjectInputStream keyin = new ObjectInputStream (new FileInputStream (args[3));
Key key = (key) keyin.readobject ();
Keyin.close ();
InputStream in = new FileInputStream (args[1]);
OutputStream out = new FileOutputStream (args[2]);
Cipher Cipher = cipher.getinstance ("AES");
Cipher.init (mode, key);
Crypt (in, out, cipher);
In.close ();
Out.close ();
} catch (IOException e) {e.printstacktrace ();
catch (Generalsecurityexception e) {e.printstacktrace ();
catch (ClassNotFoundException e) {e.printstacktrace (); }/** * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes to a * o
Utput Stream. * @param in the input stream * @param out of the output stream * @param cipher the cipher that transforms thE bytes */public static void crypt (InputStream in, outputstream out, Cipher Cipher) throws IOException, G
eneralsecurityexception {int blockSize = Cipher.getblocksize ();
int outputsize = cipher.getoutputsize (blockSize);
byte[] inbytes = new Byte[blocksize];
byte[] outbytes = new Byte[outputsize];
int inlength = 0;
Boolean more = true;
while (more) {inlength = In.read (inbytes);
if (inlength = = blockSize) {int outlength = cipher.update (inbytes, 0, BlockSize, outbytes);
Out.write (outbytes, 0, outlength);
else more = false;
if (Inlength > 0) outbytes = cipher.dofinal (inbytes, 0, inlength);
else Outbytes = cipher.dofinal ();
Out.write (outbytes);
}
}