I am trying to decrypt a text file.I have the original text and the encrypted one ,plus the encryption code itself.I think it is similar to XOR
cipher but I am not sure.I read about Known-plaintext attack but wasn't able to find good example to try and implement in my task.
I know java is using linear congruential formula and that I can use brute force to find the key for the decryption.
In my code I was trying to play with the seed .I tried to compare to strings each time after decryption was made but I did not succeed.Any help would be much appreciated.
public class test {
public static int KEY = 0; // enter code here
public static Random _rand = new Random(KEY);
private static int counter = 0;
public static void main(String[] args) throws Exception {
init_seed();
simple_test0();
decMSG();
}
public static void init_seed() {
_rand = new Random(KEY);
}
public static void simple_test0() {
String [] msg = {"Iron Beast"};
int len = msg.length;
String[] msg_enc = new String[len];
init_seed();
for(int i = 0; i < len; i++) {
msg_enc[i] = enc(msg[i]);
}
init_seed();
System.out.println(_rand);
for(int i=0;i<len;i++) {
String se2 = enc(msg_enc[i]);
System.out.println(i+") orig: "+msg[i]+"\n"+" enc(orig): "+msg_enc[i]+"\n"+" enc(enc(orig)): "+se2);
System.out.println();
}
}
public static String enc(String msg) {
String ans ="";
for(int i = 0; i < msg.length(); i++) {
char c = msg.charAt(i);
int s = c;
int rd = _rand.nextInt() % (256*256);
int s2 = s ^ rd;
char c2 = (char) (s2);
ans += c2;
}
return ans;
}
public static void decMSG() throws Exception {
boolean ans = false;
String file_name = "msg";
String msg = "first text line";
FileReader fr = new FileReader(file_name);
BufferedReader is = new BufferedReader(fr);
String s = is.readLine();
int key = 0;
while(ans == false ) {
KEY =key;
s = enc(s);
if(msg.equals(s)) {
System.out.println(s + "\t" + KEY);
ans = true;
counter++;
}
_rand = new Random(key);
System.out.println( KEY);
if(key > 10000000) {
key=0;
}
key++;
}
System.out.println(counter);
is.close();
fr.close();
}
}
Related
I am trying to link two files together and have one count the amount of characters and have the other one give the answer to the character counter. The first file cant have the word that is being given to be displayed as well. How would I go about doing so?
File one
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
System.out.println("Line " + (answer + 1));
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("The specific Line is: " + text);
}
File two
public class countWords
{
public static void main(String[] args) {
String string = "nose";
int count = 0;
//Counts each character except space
string = string.replaceAll(" ", "");
count = string.length();
//Displays the total number of characters present in the given string
System.out.println("Total number of characters in a string: " + count);
}
}
Figured it out for the first file
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
WordCounter wc = new WordCounter(text);
wc.removeSpaces();
wc.count();
int letters = wc.getCount();
System.out.println("The amount of characters is:" + letters);
}
}
Got the second file
public class WordCounter
{
private final String word;
private int count = 0;
public WordCounter(String word) {
this.word = word;
}
public void removeSpaces() {
word.replaceAll(" ", "");
}
public void count() {
count = word.length();
}
public int getCount() {
return count;
}
}
I want to develop a OTPInputStream in Java that extends the InputStream and takes another input stream of key data and provides a stream encrypting / decrypting input stream.I need to develop a test program to show the use of OTPInputStream that uses XOR and arbitrary data.
I tried with this code but I have problem that is
java.io.FileInputStream cannot be cast to java.lang.CharSequence
What should I do here?
public class Bitwise_Encryption {
static String file = "" ;
static String key = "VFGHTrbg";
private static int[] encrypt(FileInputStream file, String key) {
int[] output = new int[((CharSequence) file).length()];
for(int i = 0; i < ((CharSequence) file).length(); i++) {
int o = (Integer.valueOf(((CharSequence) file).charAt(i)) ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
output[i] = o;
}
return output;
}
private static String decrypt(int[] input, String key) {
String output = "";
for(int i = 0; i < input.length; i++) {
output += (char) ((input[i] - 48) ^ (int) key.charAt(i % (key.length() - 1)));
}
return output;
}
public static void main(String args[]) throws FileNotFoundException {
FileInputStream file = new FileInputStream("directory");
encrypt(file,key);
//decrypt();
int[] encrypted = encrypt(file,key);
System.out.println("Encrypted Data is :");
for(int i = 0; i < encrypted.length; i++)
System.out.printf("%d,", encrypted[i]);
System.out.println("");
System.out.println("---------------------------------------------------");
System.out.println("Decrypted Data is :");
System.out.println(decrypt(encrypted,key));
}
}
Think what you want is just file.read() and file.getChannel().size() to read one character at a time and get the size of the file
Try something like this:
private static int[] encrypt(FileInputStream file, String key) {
int fileSize = file.getChannel().size();
int[] output = new int[fileSize];
for(int i = 0; i < output.length; i++) {
char char1 = (char) file.read();
int o = (char1 ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
output[i] = o;
}
return output;
}
Will have to do some error handling because file.read() will return -1 if the end of the file has been reached and as pointed out reading one byte at a time is lot of IO operations and can slow down performance. You can keep the data in a buffer and read it another way like this:
private static int[] encrypt(FileInputStream file, String key) {
int fileSize = file.getChannel().size();
int[] output = new int[fileSize];
int read = 0;
int offset = 0;
byte[] buffer = new byte[1024];
while((read = file.read(buffer)) > 0) {
for(int i = 0; i < read; i++) {
char char1 = (char) buffer[i];
int o = (char1 ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
output[i + offset] = o;
}
offset += read;
}
return output;
}
This will read in 1024 bytes at a time from the file and store it in your buffer, then you can loop through the buffer to do your logic. The offset value is to store where in our output the current spot is. Also you will have to make sure that i + offset doesn't exceed your array size.
UPDATE
After working with it; i decided to switch to Base64 Encoding/Decoding to remove non-printable characters:
private static String encrypt(InputStream file, String key) throws Exception {
int read = 0;
byte[] buffer = new byte[1024];
try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
while((read = file.read(buffer)) > 0) {
baos.write(buffer, 0, read);
}
return base64Encode(xorWithKey(baos.toByteArray(), key.getBytes()));
}
}
private static String decrypt(String input, String key) {
byte[] decoded = base64Decode(input);
return new String(xorWithKey(decoded, key.getBytes()));
}
private static byte[] xorWithKey(byte[] a, byte[] key) {
byte[] out = new byte[a.length];
for (int i = 0; i < a.length; i++) {
out[i] = (byte) (a[i] ^ key[i%key.length]);
}
return out;
}
private static byte[] base64Decode(String s) {
return Base64.getDecoder().decode(s.trim());
}
private static String base64Encode(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
This method is cleaner and doesn't require knowing the size of your InputStream or do any character conversions. It reads your InputStream into an OutputStream to do the Base64 Encoding as well to remove non printable characters.
I have tested this and it works both for encrypting and decrypting.
I got the idea from this answer:
XOR operation with two strings in java
I need to write a simple Caesar cipher for an assignment and I have to encrypt the message "This is a Caesar cipher" with a left shift of 3. I have tried using an IF statement followed by 'continue;' but it is not working, I cannot for the life of me figure out what is causing this problem haha.
public static String encrypt(String plainText, int shiftKey) {
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++) {
char replaceVal = plainText.charAt(i);
int charPosition = ALPHABET.indexOf(replaceVal);
if(charPosition != -1) {
int keyVal = (shiftKey + charPosition) % 26;
replaceVal = ALPHABET.charAt(keyVal);
}
cipherText += replaceVal;
}
return cipherText;
}
public static void main (String[] args) {
String message;
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter a sentence to be encrypted");
message = new String();
message = sc.next();
}
System.out.println("The encrypted message is");
System.out.println(encrypt(message, 23));
}
}
You are only reading one word with Scanner.next() and never use new String(). Change
message = new String();
message = sc.next();
to
message = sc.nextLine();
It's also worth noting that StringBuilder and simple arithmetic is all you need for a Caesar Cipher. For example,
public static String encrypt(String plainText, int shiftKey) {
StringBuilder sb = new StringBuilder(plainText);
for (int i = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (!Character.isWhitespace(ch)) {
sb.setCharAt(i, (char) (ch + shiftKey));
}
}
return sb.toString();
}
public static void main(String[] args) {
int key = 10;
String enc = encrypt("Secret Messages Are Fun!", key);
System.out.println(enc);
System.out.println(encrypt(enc, -key));
}
Which outputs
]om|o~ Wo}}kqo} K|o Px+
Secret Messages Are Fun!
I am trying to design a program that takes data from an external file, stores the variable to arrays and then allows for manipulation.sample input:
String1 intA1 intA2
String2 intB1 intB2
String3 intC1 intC2
String4 intD1 intD2
String5 intE1 intE2
I want to be able to take these values from the array and manipulate them as follows;
For each string I want to be able to take StringX and computing((intX1+
intX2)/)
And for each int column I want to be able to do for example (intA1 + intB1 + intC1 + intD1 + intE1)
This is what I have so far, any tips?
**please note java naming conventions have not been taught in my course yet.
public class 2D_Array {
public static void inputstream(){
File file = new File("data.txt");
try (FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != -1) {
readLines("data.txt");
FivebyThree();
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static int FivebyThree() throws IOException {
Scanner sc = new Scanner(new File("data.txt"));
int[] arr = new int[10];
while(sc.hasNextLine()) {
String line[] = sc.nextLine().split("\\s");
int ele = Integer.parseInt(line[1]);
int index = Integer.parseInt(line[0]);
arr[index] = ele;
}
int sum = 0;
for(int i = 0; i<arr.length; i++) {
sum += arr[i];
System.out.print(arr[i] + "\t");
}
System.out.println("\nSum : " + sum);
return sum;
}
public static String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
lines.add(line);
}
return lines.toArray(new String[lines.size()]);
}
/* int[][] FivebyThree = new int[5][3];
int row, col;
for (row =0; row < 5; row++) {
for(col = 0; col < 3; col++) {
System.out.printf( "%7d", FivebyThree[row][col]);
}
System.out.println();*/
public static void main(String[] args)throws IOException {
inputstream();
}
}
I see that you read data.txt twice and do not use first read result at all. I do not understand, what you want to do with String, but having two-dimension array and calculate sum of columns of int is very easy:
public class Array_2D {
static final class Item {
final String str;
final int val1;
final int val2;
Item(String str, int val1, int val2) {
this.str = str;
this.val1 = val1;
this.val2 = val2;
}
}
private static List<Item> readFile(Reader reader) throws IOException {
try (BufferedReader in = new BufferedReader(reader)) {
List<Item> content = new ArrayList<>();
String str;
while ((str = in.readLine()) != null) {
String[] parts = str.split(" ");
content.add(new Item(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
}
return content;
}
}
private static void FivebyThree(List<Item> content) {
StringBuilder buf = new StringBuilder();
int sum1 = 0;
int sum2 = 0;
for (Item item : content) {
// TODO do what you want with item.str
sum1 += item.val1;
sum2 += item.val2;
}
System.out.println("str: " + buf);
System.out.println("sum1: " + sum1);
System.out.println("sum2: " + sum2);
}
public static void main(String[] args) throws IOException {
List<Item> content = readFile(new InputStreamReader(Array_2D.class.getResourceAsStream("data.txt")));
FivebyThree(content);
}
}
I'm going to show all of my code here so you guys get a gist of what I'm doing.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
List<String> foo = new ArrayList<String>();
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
// String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.size() - blockSize; k++) {
list.add(foo.toString().substring(k, k+blockSize));
}
System.out.println(list);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z]","").toLowerCase());
}
return myList;
}
}
This is the code that is using substring.
int blockSize = Integer.valueOf(args[2]);
//"foo" is an ArrayList<String> which I have to convert toString() to use substring().
String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < line.length() - blockSize; k++) {
list.add(line.substring(k, k+blockSize));
}
System.out.println(list);
When I specify blockSize as 4 in cmd this is the result:
[[, a, , ab, abc ]
the text file (standardised using my other code) is this:
abcdzaabcdd
so the result should be this:
[abcd, bcdz, cdza, ] etc.
Any help?
Thanks in advance.
Here is code showing how to improve a little your code. Main change is returning simplified string from simplify method instead of List<String> of simplified lines, which after converting it to string returned String in form
[value0, value1, value2, ...]
Now code returns String in form value0value1value2.
Another change is lowering indentation lever by removing unnecessary else if statement and braking control flow with System.exit(0); (you can also use return; here).
class Plagiarism {
public static void main(String[] args) throws Exception {
//you are not using 'myPlag' anywhere, you can safely remove it
// Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
System.exit(0);
}
String foo = null;
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader(new FileReader(args[i]));
foo = simplify(reader);
System.out.println(foo);
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.length() - blockSize; k++) {
list.add(foo.toString().substring(k, k + blockSize));
}
System.out.println(list);
}
public static String simplify(BufferedReader input)
throws IOException {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = input.readLine()) != null) {
sb.append(line.replaceAll("[^a-zA-Z]", "").toLowerCase());
}
return sb.toString();
}
}