Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.Random;
- public class CCrypt {
- public static void main(String[] args) {
- if (args.length < 2) {
- System.err
- .println("Usage: java CCrypt <file1> <file2>\n"
- + "You will get one file called C, containing the cryptotext, "
- + "one file called K which decrypts C into M and "
- + "one file called K2 which decrypts C into M2.");
- System.exit(-1);
- }
- File f1 = new File(args[0]);
- File f2 = new File(args[1]);
- if (f1.length() > f2.length()) {
- File temp = f1;
- f1 = f2;
- f2 = temp;
- }
- doFirst(f1);
- doSecond(f2);
- }
- private static void doSecond(File f2) {
- try {
- /**
- * From M2 and C we create K2 by K2 = M2 + C. Then M2 = C + K2 and M
- * = C + K
- */
- DataInputStream crypt = new DataInputStream(
- new FileInputStream("C"));
- DataInputStream in = new DataInputStream(new FileInputStream(f2));
- DataOutputStream key = new DataOutputStream(new FileOutputStream(
- "K2"));
- key.writeInt(f2.getName().length());
- for (int l = 0; l < f2.getName().length(); l++)
- key.writeChar(f2.getName().charAt(l));
- int b;
- while ((b = in.read()) >= 0) {
- key.write(b ^ crypt.read());
- }
- crypt.close();
- in.close();
- key.close();
- } catch (FileNotFoundException e) {
- System.err.println("File not found: " + f2);
- System.exit(-1);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static void doFirst(File f1) {
- try {
- /**
- * From M and a random K we create C, by C = M ^ K.
- */
- Random rand = new Random();
- DataOutputStream crypt = new DataOutputStream(new FileOutputStream(
- "C"));
- DataInputStream in = new DataInputStream(new FileInputStream(f1));
- DataOutputStream key = new DataOutputStream(new FileOutputStream(
- "K"));
- key.writeInt(f1.getName().length());
- for (int l = 0; l < f1.getName().length(); l++)
- key.writeChar(f1.getName().charAt(l));
- int b;
- while ((b = in.read()) >= 0) {
- int k = rand.nextInt();
- key.write(k);
- crypt.write(b ^ k);
- }
- crypt.close();
- in.close();
- key.close();
- } catch (FileNotFoundException e) {
- System.err.println("File not found: " + f1);
- System.exit(-1);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement