Skip to content

Instantly share code, notes, and snippets.

@cyberterror
Created July 28, 2016 10:13
Show Gist options
  • Save cyberterror/6cf51bf91df57ff501d9c5a1c9289a75 to your computer and use it in GitHub Desktop.
Save cyberterror/6cf51bf91df57ff501d9c5a1c9289a75 to your computer and use it in GitHub Desktop.
package com.javarush.test.level18.lesson10.bonus01;
/* Шифровка
Придумать механизм шифровки/дешифровки
Программа запускается с одним из следующих наборов параметров:
-e fileName fileOutputName
-d fileName fileOutputName
где
fileName - имя файла, который необходимо зашифровать/расшифровать
fileOutputName - имя файла, куда необходимо записать результат шифрования/дешифрования
-e - ключ указывает, что необходимо зашифровать данные
-d - ключ указывает, что необходимо расшифровать данные
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Будем использовать забавную реализацию шифра Вернама.
* Шифр требует одинаковую длину ключа и сообщения
* Потом ксорится ключ с сообщением
*
* Расшифровывается аналогично, ксорим шифрованное сообщение и ключ
* */
public class Solution {
/** Эта строка будет ключом */
public static final String KEY = "onetimepad";
public static void main(String[] args) throws IOException
{
byte[] source;
byte[] target;
FileInputStream fileInputStream = new FileInputStream(args[1]);
source = new byte[fileInputStream.available()];
fileInputStream.read(source);
fileInputStream.close();
/**
* Так как ключ по длине может быть меньше шифруемой строки, то мы просто повторяем ключ во временную
* строку следующим образом:
* (длина шифруемой строки) / (длина ключа) + 1
* */
byte[] tempKey = new byte[source.length];
String tempstring = "";
if (tempKey.length > KEY.length()) {
int factor = tempKey.length / KEY.length() + 1;
tempstring = new String(new char[factor]).replace("\0", KEY);
}
else {
tempstring = KEY;
}
/**
* Замет получаем из временной строки массив байтов равный по длине массиву байтов который получили
* из файла
* */
for (int index = 0; index < tempKey.length; index ++) {
tempKey[index] = (byte) tempstring.charAt(index);
}
switch (args[0]) {
/** Случай для шифрования файла */
case "-e" : {
/**
* Все теперь можно шифровать. Делается это побитовым ксором байтов ключа и строки
* */
target = new byte[source.length];
for (int index = 0; index < target.length; index++) {
target[index] = (byte) (source[index] ^ tempKey[index]);
}
/** Пишем результат в файл */
FileOutputStream fileOutputStream = new FileOutputStream(args[2]);
fileOutputStream.write(target);
fileOutputStream.close();
break;
}
/** Случай для дешифования файла */
case "-d" : {
/**
* Все теперь можно расшифровать. Делается это побитовым ксором байтов ключа и шифрованной строки
* */
target = new byte[source.length];
for (int index = 0; index < target.length; index++) {
target[index] = (byte) (source[index] ^ tempKey[index]);
}
/** Пишем результат в файл */
FileOutputStream fileOutputStream = new FileOutputStream(args[2]);
fileOutputStream.write(target);
fileOutputStream.close();
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment