How to change an encrypted message back to decrypted message? - java

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

Related

How to replace a word based on its length?

All words having the given length wordLength in the string sentence must be replaced with the word myWord. All parameters come from user input and may vary. I have tried this way but it only returns the initial string with the initial words.
Here is my source code:
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
String sentence = "";
int wordLength = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLength = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
Text myText = new Text(myWord, sentence, wordLength);
myText.changeSentence();
System.out.println("New string" + myText.getSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getSentence() {
return newSentence;
}
public void changeSentence() {
int firstPos = 0;
int i;
for (i = 0; i < mySentence.length(); i++) {
if (mySentence.charAt(i) == ' ') {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
} else if (i == mySentence.length() - 1) {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
}
}
}
}
I changed your code a little bit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
String sentence = "";
int wordLenght = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
try {
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLenght = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Text myText = new Text(myWord, sentence, wordLenght);
System.out.println(myText.getChangeSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getChangeSentence() {
String[] words = mySentence.split(" ");
for(int i = 0 ; i < words.length ; i++) {
if(words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
for (String word : words) {
newSentence += word + " ";
}
return newSentence;
}
}
Input : This is a test
word length : 2
word to replace : ii
output: This ii a test
As I can see the only separator of words that is currently considered to appear in the input text is a single white space " ". If that's true, then the changeSentence method can be quite short. There is no need to do parse the sentence character by characted. Having in mind that the white space is a separator, you can simply split the sentence by the characted " " and collect them as words. After that you can just iterate through words and replace ones that lenght matches given input characters number. After that, you can just join words together with the previously used separator and that's it.
Examples if you want to try with loops
public void changeSentence() {
final String[] words = mySentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
newSentence = String.join(" ", words);
}
or with regular expressions
public void changeSentence() {
String regex = "\\b\\w{" + charNumber+ "}\\b";
newSentence = mySentence.replaceAll(regex, wordToChange);
}
or with the stream API
public void changeSentence() {
newSentence = Arrays.stream(mySentence.split(" "))
.map(s -> s.length() == charNumber ? wordToChange : s)
.collect(Collectors.joining(" "));
}

Encode cipher class with bitwise operators

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())));
}

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;
}

How to decode to UTF-8 String from Hex encoded string

I get the HTML Javascript string such as :
htmlString = "https\x3a\x2f\x2ftest.com"
But I want to decode it as below :
str = "https://test.com"
That means , I want a Util API like :
public static String decodeHex(String htmlString){
// do decode and converter here
}
public static void main(String ...args){
String htmlString = "https\x3a\x2f\x2ftest.com";
String str = decodeHex(htmlString);
// str should be "https://test.com"
}
Does anybody know how to implement this API - decodeHex ?
This should be enough to get you started. I leave implementing hexDecode and sorting out malformed input as an exercise for you.
public String decode(String encoded) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encoded.length(); i++) {
if (encoded.charAt(i) == '\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
sb.append(hexDecode(encoded.substring(i + 2, i + 4)));
i += 3;
} else {
sb.append(encoded.charAt(i));
}
}
return sb.toString;
}
public String decode(String encoded) throws DecoderException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encoded.length(); i++) {
if (encoded.charAt(i) == '\\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
sb.append(new String(Hex.decodeHex(encoded.substring(i + 2, i + 4).toCharArray()),StandardCharsets.UTF_8));
i += 3;
} else {
sb.append(encoded.charAt(i));
}
}
return sb.toString();
}

Encryption/Decryption in java

Hi i found some code after do some Google and i am using this code to Encrypt the string (witch i set as parameter in web-service)
and it's working fine, it's to hard for me to understand this code so put hole class.
public class RSA {
Vector<Object> vectEnc;
Object enc[];
private long P, Q;
private long N, M, E = 11;
private long D;
public RSA() {
P = 6151;
Q = 8807;
N = P * Q;
M = (P - 1) * (Q - 1);
E = 11;
D = 44310191;
vectEnc = new Vector<Object>();
}
public String doEncryption(String message) {
try {
String str = new BASE64Encoder().encode(message.getBytes("UTF-8"));
String encString = "";
for (int i = 0; i < str.length(); i += 3) {
String tempAsci = "1";
String tempStr;
for (int h = 0; h < 3; h++) {
int total = i + h;
if (total < str.length()) {
tempStr = String.valueOf((int) (str.subSequence(total,
total + 1).charAt(0)) - 30);
if (tempStr.length() < 2) {
tempStr = "0" + tempStr;
}
} else {
break;
}
tempAsci = tempAsci + tempStr;
}
vectEnc.add(tempAsci + "1");
}
enc = vectEnc.toArray();
vectEnc.removeAllElements();
for (int i = 0; i < enc.length; i++) {
long base = Long.parseLong(enc[i].toString());
long powMod = powMod(base, E, N);
encString = encString + String.valueOf(powMod) + " ";
}
return encString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String doDecryption(String codeMsg) {
String[] decryptArray = codeMsg.split(" ");
String decryptStr = "";
String originalStr = "";
for (int i = 0; i < decryptArray.length; i++) {
long base = Long.parseLong(decryptArray[i]);
long powMod = powMod(base, D, N);
String powModString = String.valueOf(powMod);
decryptStr = decryptStr
+ powModString.subSequence(1, powModString.length() - 1);
}
for (int i = 0; i < decryptStr.length(); i += 2) {
char ch = (char) (Integer.parseInt(decryptStr.subSequence(i, i + 2)
.toString()) + 30);
originalStr = originalStr + ch;
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] decBytes = null;
try {
decBytes = decoder.decodeBuffer(originalStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String decodeStr = new String(decBytes);
return decodeStr;
}
public long powMod(long base, long exp, long modula) {
long accum = 1;
int i = 0;
long base2 = base;
while ((exp >> i) > 0) {
if (((exp >> i) & 1) == 1) {
accum = mo((accum * base2), modula);
}
base2 = mo((base2 * base2), modula);
i++;
}
return accum;
}
public long mo(long g, long l) {
return (long) (g - (l * Math.floor(g / l)));
}
}
But the problem is when the String Length is more the 56 it throw the Exception Like
java.lang.NumberFormatException: For input string: "174-17-201"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.info.test.RSA.doEncryption(RSA.java:49)
at com.info.test.Test.main(Test.java:56)
i even no what is the algorithm is use by this code ,i do some Google and i found simple solution is make a part of string and do Encryption it Like this.
int MAX_LAN = 55;
List<String> splitEqually = splitEqually(string,MAX_LAN);
String encodeString = "";
for (int i = 0; i < splitEqually.size(); i++) {
encodeString +=rsa.doEncryption(splitEqually.get(i));
}
System.out.println(encodeString);
public static List<String> splitEqually(String text, int size) {
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
return ret;
}
and it working fine , so is it proper method or not ??
I would strongly suggest using Java's built-in cryptographic libraries for this. Follow this series of articles on how to perform RSA encryption/decryption in Java:
http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml

Categories

Resources