Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

String XOR Method

Posted on 2000-05-12
Medium Priority
4,173 Views
Hi,

I'm looking for a method that makes a XOR operation between 2 String with the following signature : String xor(String str, String key); and used like this :

String myStr = "treteterterterterter";
String myKey = "terwb897856304984erzvgtze";

String myCodedStr = xor(myStr,myKey);
String myDecodedStr = xor(myCodedStr, myKey);

Note that myDecodedStr is equals to myStr.

It's quitely URGENT for me, so that's why I give 300 points for the source code.

Thanks
0
Question by:baresse
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
1 Comment

LVL 9

Accepted Solution

doronb earned 1200 total points
ID: 2803998
Hi baresse,

Try the following method:

public String xor(String str, String key) {
String result = null;
byte[] strBuf = str.getBytes();
byte[] keyBuf = key.getBytes();
int c = 0;
int z = keyBuf.length;
ByteArrayOutputStream baos = new ByteArrayOutputStream(strBuf.length);
for (int i = 0; i < strBuf.length; i++) {
byte bS = strBuf[i];
byte bK = keyBuf[c];
byte bO = (byte)(bS ^ bK);
if (c < z - 1) {
c++;
} else {
c = 0;
}
baos.write(bO);
}
try {
baos.flush();
result = baos.toString();
baos.close();
baos = null;
} catch (IOException ioex) {
}
return result;
}

The idea is to convert the string and the key to byte arrays, then you XOR each byte of the string with the corresponding byte from the key, when you "run-out" of key-bytes you just start over from the start of the key ;)

Regards and good luck,

Doron
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month11 days, 5 hours left to enroll