Encode cipher class with bitwise operators - java

How can I modify the following program so that it uses an eight-character string as the key?
public class SelfTest {
public static void main(String[] args) {
String msg = "This is a test";
String encmsg = "";
String decmsg = "";
int key = 88;
System.out.println("Original msg: " + msg);
for(int i=0; i< msg.length(); i++){
encmsg = encmsg + (char) (msg.charAt(i)^key);
}
System.out.println("Encode msg: " + encmsg);
}
}

You could use each character in the key individually and wrap around it when it's done. E.g.:
for(int i=0; i< msg.length(); i++){
encmsg = encmsg +
(char) (msg.charAt(i) ^ (key.charAt(i % key.length())));
}

Related

How to change an encrypted message back to decrypted message?

This is a code I used to encrypt a message entered by a user in a text box. Im wondering how to make a code like this, but instead, take an encrypted message, insert it in a new text box and turn it into a decrypted message.
private void btnDecryptActionPerformed(java.awt.event.ActionEvent evt) {
String origMessage;
String encMessage = "";
char tempChar;
int tempAscii;
origMessage = txtDecrypt.getText();
for (int i = 0; i < origMessage.length(); i = i + 1) {
tempChar = origMessage.charAt(i);
tempAscii = (int) tempChar;
tempAscii = tempAscii + 3;
tempChar = (char) tempAscii;
encMessage = encMessage + tempChar;
}
if (origMessage.length() < 30) {
fTxtEncrypt.setText(encMessage);
} else {
fTxtEncrypt.setText("Must be less than 30 characters...");
}
}
The Caesar cipher shifts each character by a certain number of characters. To decrypt this message, you have to shift them back by the same number of characters:
public static void main(String[] args) {
String encrypted = caesarCipher("message", 3);
String decrypted = caesarCipher(encrypted, -3);
System.out.println(encrypted); // phvvdjh
System.out.println(decrypted); // message
}
public static String caesarCipher(String source, int shift) {
StringBuilder target = new StringBuilder(source.length());
for (int i = 0; i < source.length(); i++) {
target.append((char) (source.charAt(i) + shift));
}
return target.toString();
}
For decrypting you need to do tempAscii - 3
Example :
public class Test {
public static void main(String args[]) throws Exception {
String origMessage = "Hello world";
String encMessage = encrypt(origMessage);
System.out.println("encrypt message :" + encMessage);
System.out.println("decrypt message :" + decrypt(encMessage));
}
static String decrypt(String encMessage) throws Exception {
return encryptOrDecrypt(encMessage, "decrypt");
}
static String encrypt(String encMessage) throws Exception {
return encryptOrDecrypt(encMessage, "encrypt");
}
private static String encryptOrDecrypt(String message, String type)
throws Exception {
char tempChar;
int tempAscii;
String resultMessage = "";
for (int i = 0; i < message.length(); i = i + 1) {
tempChar = message.charAt(i);
tempAscii = (int) tempChar;
if (type.equals("encrypt")) {
tempAscii = tempAscii + 3;
} else {
tempAscii = tempAscii - 3;
}
tempChar = (char) tempAscii;
resultMessage = resultMessage + tempChar;
}
if (message.length() < 30) {
return resultMessage;
} else {
throw new Exception("Must be less than 30 characters...");
}
}
}
Output:
encrypt message :Khoor#zruog
decrypt message :Hello world

Vigenere Cipher Algorithm In Java - Decrypted Message to Plaintext

I am currently trying to write the Vigenere Cipher algorithm in Java. I have to change the decrypted message to the plaintext but having trouble. Below is what I have so far.
When I run it, the message is not deciphered properly.
import java.util.Scanner;
public class VigenereCipher {
public static void main(String arg[]) {
String message = "";
String keyword = "KISWAHILI";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a message: ");
message = sc.nextLine();
char msg[] = message.toCharArray();
int msgLength = msg.length;
char key[] = new char [msgLength];
char decryptedText[] = new char[msgLength];
for(int i = 0, j = 0; i < msgLength; i++, j++) {
if(j == keyword.length()) {
j = 0;
}
key[i] = keyword.charAt(j);
}
// Decryption Code
for(int i =0; i < msgLength; i++) {
decryptedText[i] = (char)(((key[i] + 26) % 26) + 'A');
}
System.out.println("Decrypted Message: " + message);
System.out.println("Keyword: " + keyword);
System.out.println("Plaintext: " + String.valueOf(decryptedText));
}
}
It seems that whitespaces need to be skipped while populating key array:
for (int i = 0, j = 0; i < msgLength; i++) {
if (msg[i] == ' ') {
key[i] = ' ';
} else {
key[i] = keyword.charAt(j++ % keyword.length());
}
}
System.out.println("Key Message: " + new String(key));
Similarly, it needs to be taken into account in the decrypting loop.
And decryption has to be fixed:
Di = (Mi - Ki + 26 ) mod 26
for (int i =0; i < msgLength; i++) {
char c = msg[i];
decryptedText[i] = c == ' ' ? c : (char)(((msg[i] - key[i] + 26) % 26) + 'A');
}
Upon applying these changes, the output is as follows:
Key Message: KISW AH ILIKI SW AHILIKIS WAH ILI KISW AHILIKISW AHIL IKIS
Encrypted Message: XQKP IZ IMWEB LK AUVZCXKW PHL VPE RIKD ASOZZSBZI TOIE ESTD
Keyword: KISWAHILI
Plaintext: NIST IS ABOUT TO ANNOUNCE THE NEW HASH ALGORITHM THAT WILL

How do I truncate a string, add the value to an Array, and delete the value?

I'm working on a converter in Java that would convert ASCII values to RGB. My specific problem arises when I try to truncate the Hex data. Basically, I want to create a system that would loop through the data, convert it into 6 digit blocks, and add it to an Array. While creating a separate String for the extra data. Here's my code:
package converter;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
public class ASCIItoRGB{
public static void main(String args[]) {
// Input
String asciiValue = "2121876";
char[] c = asciiValue.toCharArray();
StringBuffer hexValue = new StringBuffer();
for(int i=0; i<c.length; i++) {
hexValue.append(Integer.toHexString((int)c[i]));
}
String hexString = hexValue.toString();
String hexTruncated = hexValue.toString();
ArrayList rgbValues = new ArrayList();
for(int i=0; i<hexString.length(); i++) {
if(hexTruncated.length() >= 6) {
String tempval = hexTruncated.substring(0, 5);
rgbValues.add(Color.decode(tempval));
tempval = hexTruncated.substring(tempval.length(), 5);
}
else {
}
}
// Output
System.out.println("ASCII VALUE: " + asciiValue);
System.out.println("CHAR ARRAY: " + Arrays.toString(c));
System.out.println("HEX VALUE: " + hexString);
System.out.println("RGB VALUES: " + rgbValues.toString());
}
}
Okay. I got it to work by using a while loop. I also changed tempval to equal a substring of hexString using the legnth of itself, and the legnth of hexString.
// ASCII to Hex
char[] c = asciiValue.toCharArray();
StringBuffer hexValue = new StringBuffer();
for(int i=0; i<c.length; i++) {
hexValue.append(Integer.toHexString((int)c[i]));
}
String hexString = hexValue.toString();
// Hex to RGB
ArrayList<Color> rgbValues = new ArrayList<Color>();
while(hexString.length() >= 6) {
String tempval = hexString.substring(0,6);
rgbValues.add(Color.decode(tempval));
hexString = hexString.substring(tempval.length(), hexString.length());
if(hexString.length() < 6) {
String hexExtra = hexString;
System.out.println("EXTRA DATA: " + hexExtra);
}
}

Effective ways to find partial sha1 collision

I need to find 2 different string and compare their hash value. Both string must contain "abc". I looking for the first eight character that are the same and stop. I have been running for more than 24 hours and still not found. My code has no problem running but i am wondering is there any more effective ways to find the collision
public static void main(String[] args) {
String message1 = "abc";
String message2 = "abc";
int x=0;
if (message1.equals(message2)) {
String temp1 = message1 + x;
String temp2 = x + message2;
String result1 = sha1Hashing(temp1);
String result2 = sha1Hashing(temp2);
while (!result1.equals(result2)){
temp1 = message1 + x;
temp2 = x + message2;
result1 = sha1Hashing(temp1);
result2 = sha1Hashing(temp2);
System.out.println("First message = " + temp1 + " Second message = " + temp2 + "\n");
System.out.println("First hash = " + result1);
System.out.println("Second hash = " + result2 + "\n");
x++;
if(result1.equals(result2)){
System.out.println("FOUND!!");
System.exit(0);
}
}
}
}
public static String sha1Hashing (String message) {
String sha1 = "";
StringBuffer sb = new StringBuffer();
try {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(message.getBytes());
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
//return first 8 char
sha1 = sb.toString().substring(0,8);
return sha1;
}

Multiline strings concatenation in Java

I'm looking for some help. What is the easiest way to concatenate multiline strings in Java and print it after ?
For example : I've got two strings :
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
And I want to get this result in the Java Eclipse console :
_ _
.-./*) .-./*)
_/___\/ _/___\/
U U U U
I've already try some algorithms to divide my strings in differents parts and after re-concatenate it. But it was without success.
I know there are StringBuffer class and StringBuilder class but after some research, I didn't found something that correspond to my need.
Thanks in advance for your help.
See my example below, should be self explaining.
public class Turtle {
private static final String returnpattern = "\r\n";
public static void main(String[] args) {
// the data to run through
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
// split the data into individual parts
String[] one = turtle1.split(returnpattern);
String[] two = turtle2.split(returnpattern);
// find out the longest String in data set one
int longestString = 0;
for (String s : one) {
if (longestString < s.length()) {
longestString = s.length();
}
}
// loop through parts and build new string
StringBuilder b = new StringBuilder();
for (int i = 0; i < one.length; i++) {
String stringTwo = String.format("%1$" + longestString + "s", two[i]); // left pad the dataset two to match
// length
b.append(one[i]).append(stringTwo).append(returnpattern);
}
// output
System.out.println(b);
}
}
Just for fun, here is another solution using streams, prepared for more than two turtles to be shown side-by-side:
public static void main(String[] args) {
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
// split lines into fragments
List<List<String>> fragments = Stream.of(turtle1, turtle2)
.map(x -> Stream.of(x.split("\\r\\n?|\\n")).collect(Collectors.toList()))
.collect(Collectors.toList());
// make all lists same length by adding empty lines as needed
int lines = fragments.stream().mapToInt(List::size).max().orElse(0);
fragments.forEach(x -> x.addAll(Collections.nCopies(lines - x.size(), "")));
// pad all fragments to maximum width (per list)
List<List<String>> padded = fragments.stream().map(x -> {
int width = x.stream().mapToInt(String::length).max().orElse(0);
return x.stream().map(y -> String.format("%-" + width + "s", y)).collect(Collectors.toList());
}).collect(Collectors.toList());
// join corresponding fragments to result lines, and join result lines
String result = IntStream.range(0, lines)
.mapToObj(i -> padded.stream().map(x -> x.get(i)).collect(Collectors.joining()))
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(result);
}
Not so pretty but works:
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
String[] turtle1Lines = turtle1.split("\r\n");
String[] turtle2Lines = turtle2.split("\r\n");
StringBuilder sb = new StringBuilder();
int turtle1Width = 0;
for (int i = 0; i < 4; i++) {
if (turtle1Lines[i].length() > turtle1Width) {
turtle1Width = turtle1Lines[i].length();
}
}
for (int i = 0; i < 4; i++) {
sb.append(turtle1Lines[i]);
for (int j = turtle1Width - turtle1Lines[i].length(); j > 0; j--) {
sb.append(' ');
}
sb.append(turtle2Lines[i]);
sb.append("\r\n");
}
String turtles = sb.toString();
I'm here too ;)
public class Test {
static String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r".replace("\r", "");
static String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r".replace("\r", "");
public static int countRows(String string){
return string.length() - string.replace("\n", "").length() + 1;
}
public static int getMaxLength(String string){
int maxLength = 0;
int currentLength = 0;
char[] data = string.toCharArray();
for(Character c : data){
if(c != '\n'){
if(++currentLength > maxLength) {
maxLength = currentLength;
}
}else{
currentLength = 0;
}
}
return maxLength;
}
public static String[] toStringArray(String string){
int length = getMaxLength(string);
int rows = countRows(string);
String[] result = new String[rows];
int last = 0;
for(int i = 0; i < rows; i++){
int temp = string.indexOf("\n", last);
String str;
if(temp != -1) {
str = string.substring(last, temp);
}else{
str = string.substring(last);
}
while(str.length() < length){
str += " ";
}
result[i] = str;
last = temp + 1;
}
return result;
}
public static String concatMultilineStrings(String first, String second){
StringBuilder sb = new StringBuilder();
String[] arrayFirst = toStringArray(first);
String[] arraySecond = toStringArray(second);
if(arrayFirst.length != arraySecond.length){
System.exit(69);
}
for(int i = 0; i < arrayFirst.length; i++){
sb.append(arrayFirst[i]);
sb.append(arraySecond[i]);
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(concatMultilineStrings(turtle1, turtle2));
}
}

Categories

Resources