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();
}
Related
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
I have a string:
2 + 2 = ${2 + 2}
This is a ${"string"}
This is an object: ${JSON.stringify({a: "B"})}
This should be "<something>": ${{
abc: "def",
cba: {
arr: [
"<something>"
]
}
}.cba.arr[0]}
This should ${"${also work}"}
And after parsing it I should get something like that:
2 + 2 = 4
This is a string
This is an object: {"a":"B"}
This should be "<something>": <something>
This should ${also work}
So I need help implementing it in Java, I simply need to get what is between ${ and }.
I tried using a regular expression: \${(.+?)} but it fails when string inside contains }
So after a bit of testing, I've ended up with this:
ScriptEngine scriptEngine = new ScriptEngineManager(null).getEngineByName("JavaScript");
String str = "2 + 2 = ${2 + 2}\n" +
"This is a ${\"string\"}\n" +
"This is an object: ${JSON.stringify({a: \"B\"})}\n" +
"This should be \"F\": ${var test = {\n" +
" a : {\n" +
" c : \"F\"\n" +
" }\n" +
"};\n" +
"test.a.c\n" +
"}\n" +
"This should ${\"${also work}\"}"; // String to be parsed
StringBuffer result = new StringBuffer();
boolean dollarSign = false;
int bracketsOpen = 0;
int beginIndex = -1;
int lastEndIndex = 0;
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length; i++) { // i is for index
char c = chars[i];
if(dollarSign) {
if(c == '{') {
if(beginIndex == -1) {
beginIndex = i + 1;
}
bracketsOpen++;
} else if(c == '}') {
if(bracketsOpen > 0) {
bracketsOpen--;
}
if(bracketsOpen <= 0) {
int endIndex = i;
String evalResult = ""; // evalResult is the replacement value
try {
evalResult = scriptEngine.eval(str.substring(beginIndex, endIndex)).toString(); // Using script engine as an example; str.substring(beginIndex, endIndex) is used to get string between ${ and }
} catch (ScriptException e) {
e.printStackTrace();
}
result.append(str.substring(lastEndIndex, beginIndex - 2));
result.append(evalResult);
lastEndIndex = endIndex + 1;
dollarSign = false;
beginIndex = -1;
bracketsOpen = 0;
}
} else {
dollarSign = false;
}
} else {
if(c == '$') {
dollarSign = true;
}
}
}
result.append(str.substring(lastEndIndex));
System.out.println(result.toString());
I want to identify whether my string contains any hex code or not.
Use cases
String input1 = "hello check this input ";
String input2 = "hello check 0x740x680x690x73 input";
String input3 = "0x680x650x6c0x6c0x6f0x200x630x680x650x630x6b0x200x740x680x690x730x200x690x6e0x700x750x74";
isContainHex(input1) should return false
isContainHex(input2) should return true
isContainHex(input3) should return true
I have tried
String input2 = "hello check 0x740x680x690x73 input";
if(input2.contains("0x") || input2.contains("\\x"))
{
System.out.println("string contains hex");
}
and I am able to find hex but,
If My input contains hex like
String input4 = "h68h65h6ch6ch6f check this input ";
Here I cant check input4.contains("h")
Any one have solution for this?
is there any standard library by which I can achive same?
Update
I have wrote following code, and its working well but taking time.
Now can it be optimize
try
{
if (input != null && input.trim().length() > 0)
{
String originalHex = null;
StringBuilder output = new StringBuilder();
String inputArray[] = null;
if (StringUtils.countMatches(input, "\\x") > 3)
{
originalHex = input.substring(input.indexOf("\\x"), input.lastIndexOf("\\x", input.length()) + 4);
inputArray = input.split("\\Q\\x\\E");
}
else if (StringUtils.countMatches(input, "0x") > 3)
{
originalHex = input.substring(input.indexOf("0x"), input.lastIndexOf("0x", input.length()) + 4);
inputArray = input.split("0x");
}
if (inputArray != null && inputArray.length > 0)
{
for (String str: inputArray)
{
int strLength = str.trim().length();
if (strLength == 2)
{
output.append((char)Integer.parseInt(str, 16));
}
else if (strLength > 2)
{
if (strLength % 2 != 0)
{
strLength = strLength - 1;
}
for (int i = 0; i < strLength; i += 2)
{
String val = str.substring(i, i+2);
if (val.matches("\\d+"))
{
output.append((char)Integer.parseInt(val, 16));
}
}
}
}
input = input.replaceAll("\\Q" + originalHex + "\\E", output.toString());
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
syso(input);
I have 2 string which I want to join as per my requirements. Say I have
String sa = {"as,asd,asdf"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < separateds.length; i++)
{
if (separated.length == i + 1)
{
sb.append(separated[i] + "(" + separateds[i] + ")");
} else
{
sb.append(separated[i] + "(" + separateds[i] + "),");
}
}
deleteListItem.list_summ.setText(sb.toString());
it gives as(12),asd(123),asdf(1234)
But problem is , it can be like
String sa = {"as,asdf"};
String qw = {"12,123,1234"};
So in this I want like
as(12),asdf(123),1234
Try this code :
String sa = {"as,asd"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < separateds.length; i++) {
if (separated.length == i + 1) {
if(separated.length == i) {
sb.append(separateds[i] + "");
} else {
sb.append(separated[i] + "(" + separateds[i] + ")");
}
} else {
if(separated.length == i) {
sb.append("," + separateds[i]);
} else {
sb.append(separated[i] + "(" + separateds[i] + "),");
}
}
}
deleteListItem.list_summ.setText(sb.toString());
// Answer : as(12),asd(123),1234
String sa = {"as,asd,asdf"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
// first loop through separated, starting with a comma
for (int i = 0; i < separated.length; i++) {
sb.append(",").append(separated[i]).append("(").append(separateds[i]).append(")"));
}
// append remaining items in separateds
for (int i = separated.length; i < separateds.length; i++) {
sb.append(",").append(separateds[i]);
}
deleteListItem.list_summ.setText(sb.toString().substring(1)); // remove starting comma
if the lenghts of the strings are the sa, do the join
if (separated.length == i + 1 && (separated[i].lenght == separateds[i].lenght))
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