Encrypt two given strings - java

I'm trying to encrypt a message by the following code above.
Compare 2 string length and refill the short one with cycle back.
Convert that 2 string into a binary string.
XOR that 2 binary string to get another binary string.
convert the last binary string to hexadecimal.
Issue is on the last step. The output should be 111c0d131e1c180e1b10425655 instead of 111cd131e1c18e1b10425655.
Why my output missing two letters 0?
Can anyone help me to fix, please?
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main
{
public static String StringToBinary(String str)
{
StringBuilder result = new StringBuilder();
char[] ch = str.toCharArray();
for (char character : ch)
{
result.append(String.format("%8s", Integer.toBinaryString(character)).replaceAll(" ", "0"));
}
return result.toString();
}
public static String XOR(String message, String password)
{
String tmp="";
for (int i = 0; i < message.length(); i++)
{
if (message.charAt(i) == password.charAt(i))
tmp += "0";
else
tmp += "1";
}
return tmp;
}
public static String convertBinaryToHexadecimal(String binaryStr)
{
return new BigInteger(binaryStr, 2).toString(16);
}
public static void main(String[] args)
{
int idx=0;
String msg = "poiuytrewq123";
String pwd = "asdfghjkl";
for(char m:msg.toCharArray())
{
idx = (idx < pwd.length()) ? idx : 0;
char p = pwd.charAt(idx);
idx++;
String stringOfMessageCharArray = String.valueOf(m);
String stringOfPasswordCharArray = String.valueOf(p);
String messageBinaryString = StringToBinary(stringOfMessageCharArray);
String passwordBinaryString = StringToBinary(stringOfPasswordCharArray);
String XorString = XOR(messageBinaryString,passwordBinaryString);
String cipherText = convertBinaryToHexadecimal(XorString);
System.out.print(cipherText);
}
}
}

The problem is that the number you are trying to convert from binary to hex is too small to require 2 characters, so it outputs just one.
public static String convertBinaryToHexadecimal(String binaryStr)
{
String hex = new BigInteger(binaryStr, 2).toString(16);
return hex.length() < 2 ? "0" + hex : hex;
}
If you change the function to this, it will put a 0 at the front of the hex if the length is less than 2, and return the right hex.

Related

Can't compare 2 strings if a letter in first string exists in second string - java

However I had an assignment of programming in java related to a text i already have under (text).
the function is supposed to as below
getEncryptedText(int shift)
return a string representation of ciphertext given that the text to be manipulated is the plaintext using Caesar Cipher.
The number of rotation is depend on the shift value;
positive shift value represent the right rotation while negative shift value represent left
rotation. However, unlike explain in Wikipedia, this method used following string as
plain:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
Other characters than above will be treated as it is (i.e. will not been encrypted)
*Further reading: https://en.wikipedia.org/wiki/Caesar_cipher
So this is the class method I have made so far and wanted to know how can i keep the text chars which aren't included in the plaintext i have such as "!,#,#,$,%... and so on". So far i tried everything but couldn't make it but the rest seems fine!
public String getEncryptedText(int shift) {
String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
String cipherText = "";
for (int i = 0; i < text.length(); i++){
{
int charPosition = ALPHABET.indexOf(text.charAt(i));
if(text.charAt(i) == ' ') {
cipherText += " ";
}
else
{
int keyVal = (shift + charPosition) % 62;
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
}
}
return cipherText;
}
Consider modifying your if statement and using the StringBuilder class:
class Main {
public static void main(String[] args) {
CesarCypherHelper cesarCypherHelper = new CesarCypherHelper();
System.out.println(cesarCypherHelper.getEncryptedText("Hello World!", 2));
System.out.println(cesarCypherHelper.getEncryptedText("Hello World!", 64));
}
}
class CesarCypherHelper {
public String getEncryptedText(String text, int shift) {
String ALPHABET =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
StringBuilder encryptedText = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
int charPosition = ALPHABET.indexOf(ch);
if (charPosition == -1) {
encryptedText.append(ch);
} else {
int keyVal = (shift + charPosition) % ALPHABET.length();
encryptedText.append(ALPHABET.charAt(keyVal));
}
}
return encryptedText.toString();
}
}
Output:
Jgnnq Yqtnf!
Jgnnq Yqtnf!

Questions about easy "return" in JAVA

I want to make a code which has function of changing binary to decimal.
So i made a public long tonum()
and tried to return on Main method.
but there is anything shown on screen. Where is the problem?
Plz give me some hints.
public class Bitmap {
byte[] byteArr; //byte array for saving 0 or 1
char[] charArr; //char array for casting from string to byte array
public static void main(String[] args) throws Exception {
Bitmap test1 = new Bitmap("100110");
test1.tonum();
}
public Bitmap(String val) throws Exception {
byteArr = new byte[val.length()]; //To make the array length of Bitmap should e same as that of string
charArr = val.toCharArray(); //casting from string to char
for(int i = 0; i < charArr.length; i++) {
if (charArr[i] == '0')
byteArr[i] = 0;
else if (charArr[i] == '1')
byteArr[i] = 1;
else throw new Exception("Bitmap are should be sequences of zeros and ones!");
}
}
public long tonum() {
int temp = 0;
String str = "";
String str2 = "";
for (int i = 0; i < this.byteArr.length; i++){
temp = this.byteArr[i];
str = Integer.toString(temp);
str2 = str2 + str;
}
long decimal = (long)Integer.parseInt(str2,10);
System.out.println(str2);
return decimal;
}
}
long decimal = (long)Integer.parseInt(str2,10);
That doesn't change binary to decimal. It changes decimal to binary. And you don't have decimal in the first place, you have a string or presentation of binary. Try a radix of 2. But why you have both a char array and a byte array when all you do is deconstruct and reconstruct the original String is anybody's guess.

How to replace a repeated char with some characters or string

I need to replace a repeated char with $% followed by the char followed by $%.
e.g. "HELLO" will become "HE$%L$%O"
The following code that I wrote gives "HE$%L$%LO".
Please guide
int index=0;
String str1="";
String str2="";
String str4="";
String str5="";
for(int i=0;i<str.length();i++) {
char ch=str.charAt(i);
index=str.indexOf(ch);
if(index!=i) {
str4="$%"+str.charAt(index)+ "$%";
str1=str.charAt(index)+str5;
str2=str.replaceFirst(str1,str4);
}
}
return str2;
It looks like there's code missing because i can't see the duplicate character check, but what you want to do is go through str5 before you concat it and strip off all of the duplicate characters that are at the beginning. Then concat to your String.
Here a solution: Id solves the case if duplicates are more than 2 too. So remove all duplicates:
public class Converter {
public static void main(String[] args) {
final String result = replace("HELLO");
System.out.println("result = " + result);
}
private static String replace(String data) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < data.length();) {
int j = i + 1;
while (j < data.length() && data.charAt(i) == data.charAt(j)) {
j++;
}
if(j > i + 1) { // exist duplicate
stringBuilder.append("$%").append(data.charAt(i)).append("$%");
} else {
stringBuilder.append(data.charAt(i));
}
i = j;
}
return stringBuilder.toString();
}
}
And the result is:
result = HE$%L$%O

Extract numbers from an alpha numeric string using android

I have to extract only numeric values from String str="sdfvsdf68fsdfsf8999fsdf09".
How can I extract numbers from an alpha numeric string in android?
String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
update:
String str="fgdfg12°59'50\" Nfr | gdfg: 80°15'25\" Efgd";
String[] spitStr= str.split("\\|");
String numberOne= spitStr[0].replaceAll("[^0-9]", "");
String numberSecond= spitStr[1].replaceAll("[^0-9]", "");
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
public static int extractNumberFromAnyAlphaNumeric(String alphaNumeric) {
alphaNumeric = alphaNumeric.length() > 0 ? alphaNumeric.replaceAll("\\D+", "") : "";
int num = alphaNumeric.length() > 0 ? Integer.parseInt(alphaNumeric) : 0; // or -1
return num;
}
You can set the value to 0 or -1 (what to do if no number is found in the alphanumeric at all) as per your needs

How can i return value from one method to another & swapping

I have this
public class Mapper implements ScramblerIF
{
private static String map = "drsjckpwrypwsftylmzxopqtdo";
public static String charAt(String str)
{
//char[] chars = str.toCharArray();
int length = str.length();
for(int i=0; i<length; i++)
{
char aChar = str.charAt(i);
char upper = Character.toUpperCase(aChar);
int num = (upper - 'A');
char mChar = map.charAt(num);
//String chard = Character.toString(mChar);
StringBuffer buf = new StringBuffer( str);
buf.setCharAt( i, mChar );
}
return str;
}
public String scramble(String str) {
return charAt(str);
}
}
I am trying to get it to where the method
public String scramble(String str) {
return charAt(str);
}
returns the computed value from the
public static String charAt(String str)
method. Don't know where i went wrong.
Also instead of using
StringBuffer buf = new StringBuffer( str);
buf.setCharAt( i, mChar );
how would i be able to use the swap function?
When I try
char temp = chars[i];
chars[i] = chars[mChar];
chars[mChar] = temp;
I am given an ArrayIndexOutOfBoundsException.
Summary of what i am trying to do is "For each character in the original string, use its position in the alphabet to look up its replacement in the map string. For example, the string “dog” would be translated to “jtp”."
This scrables with the replacement-map you have provided. It also handles upper and lower case letters:
public class Mapper {
// abcdefghijklmnopqrstuvwxyz
private static String map = "drsjckpwrypwsftylmzxopqtdo";
public static String scramble(String str) {
if (!str.matches("[A-Za-z]*"))
throw new RuntimeException(str + " contains weird characters");
String out = "";
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
out += Character.toUpperCase(map.charAt(c - 'A'));
} else {
out += map.charAt(c - 'a');
}
}
return out;
}
public static void main(String[] args) {
System.out.println(scramble("David"));
}
}
StringBuffer.setCharAt() will throw an exception if you try to set a character beyond the buffer. You haven't put anything in the buffer.
In addition, take a look at when you are creating the buffer.

Categories