Encrypt the XML element whie writing to the file in java - java

I have java application that sending(HTTP post method) credit card numbers to the supplier via the XML.
When writing the XML file, currently credit card number also printing in the file. But it is not good practice to write the credit card numbers directly in to the file without encrypting.
I do not want to encrypt the entire XML, because we are sending the secure information through HTTPS link and hence I assume it provide necessary security. So I want to encrypt only the credit card number element while writing to the file in the Java environment.
String xmlRequest = <?xml version='1.0'?>
<ReservationRequest>
<Passenger>
<firstName>XXX</firstName>
<lastName>YYY</lastName>
</Passenger>
<CreditCard Currency='USD'>
<Number>1234567812345678</Number>
<cvv>123</cvv>
<Expiration>12/12</Expiration>
</CreditCard>
</ReservationRequest>
Please note that I want to write to file the same string that send to the supplier.

String reqXml = "" ;
String creditCardNumber = "1234567890128899" ;
reqXml = "<RentalPaymentPref>" +
"<PaymentCard CardType=\"1\" CardCode=\"VI\" CardNumber=\""+creditCardNumber+"\" ExpireDate=\"0912\" SeriesCode=\"123\">" +
"<CardHolderName>Ruchira kariyawasam</CardHolderName>" +
"</PaymentCard>" +
"</RentalPaymentPref>" ;
StringBuffer reqXmlString = new StringBuffer(reqXml.toString());
short startIndex = (short)(reqXml.indexOf("CardNumber")+12);
if(null!=creditCardNumber && (!creditCardNumber.equals("")))
{
reqXmlString.replace(startIndex,(startIndex+12),"xxxxxxxxxxxx");
}
System.out.println("reqXmlString---->"+reqXmlString);
// Remaining file writing code goes here.
Here check whether card number is blank or empty. If we get the card number, then only mask the string content while writing to the file.
Output
<RentalPaymentPref>
<PaymentCard CardType="1" CardCode="VI" CardNumber="xxxxxxxxxxxx8899" ExpireDate="0912" SeriesCode="123">
<CardHolderName>Ruchira kariyawasam</CardHolderName>
</PaymentCard>
</RentalPaymentPref>

Related

Recompute Key from another variable Key and static Key?

I'm looking a way to do something like this. I don't know how to call it, so i don't know if it exist or how to find it. Some keyword would be welcome :)
String var_1 = "user data";
String fix_1 = "supply data";
String mix = mixer(var_1,fix_1);
// mix = " something fully random "
String var_2 = "user data changed";
String fix_2 = fixer(var_2,mix);
And mix == mixer(var_2, fix_2);
So to resume, I need to generate a random data from 2 variables. 1 is variable from user and 1 is supply by me.
First time , I generate the data with these 2 variables with one function.
Then, if the user data change, with another function, I compute the new supply data with the first result and the new user data. And if I use again the computed data and the new user data, I must obtain the same data computed the first time.
Is there something to do that ? Like some cipher technique or so?
Thanks for Intel.
In fact there is something like this already which may satisfy you needs. In fact you know this function too. It's the good old XOR. And yes, it is used in crypto a lot. In fact it's the core idea of the stream ciphers and the One Time Pad.
It goes like this:
Assume you have a byte array of length n called var_1.
Assume you have a random value fix_1 of the same length.
If you do var_1 XOR fix_1 you get mix.
If you do mix XOR fix_1 you get var_1 again. (Basic math: fix_1 XOR fix_1 equals chain of zero value bytes and var_1 XOR zero bytes = var_1.
This whole thing will be as random and secure as random and secret fix_1 remains. If one of the values is not random the approach is not secure at all.
So following the idea of User253751 in comment, I was able to do it.
Step:
generate the private constant key => privateKey = encrypt(publicKey, Password_1) (the first public key is random )
if password change, generate a new public key by decoding the private constant key with password_2 => publicKey_Updated = decrypt(privateKey, Password_2)
Check if the new public key is valid : privateKey_Rebuild = encrypt(publicKey_Updated, Password_2) ====> if everything is ok, privateKey == privateKey_Rebuild.
---> I test it only with a low cryptage i use just for obfuscation, but it should work with symmetric key too. I'm not sur about Asymetric key, because to make this work, you need a crypting protocol who always give you the same crypted data with the same input. And RSA do not gave you the same crypted data even with the same input.
Here my code (not a copy/paste snippet beacause it use my own library), but you can catch the idea easily with the function name.
KeyObfusc publicKey_1 = KeyObfusc.fromPassword("publicKey_1");
KeyObfusc password_1 = KeyObfusc.fromPassword("password_1");
Encoder encoder_1 = new Encoder(password_1, CipherFormat.HEX);
Decoder decoder_1 = new Decoder(password_1, CipherFormat.HEX);
byte[] privateKey = encoder_1.toBytes(publicKey_1.getEncoded());
byte[] publicKey_1_Rebuild = decoder_1.fromBytesToBytes(privateKey);
LogDelay.send("password_1 : " + BytesTo.stringHex(password_1.getEncoded()));
LogDelay.send("publicKey_1 : " + BytesTo.stringHex(publicKey_1.getEncoded()));
LogDelay.send("privateKey : " + BytesTo.stringHex(privateKey));
LogDelay.send("publicKey_1 Rebuild : " + Arrays.equals(publicKey_1.getEncoded(), publicKey_1_Rebuild) +
" " + BytesTo.stringHex(publicKey_1_Rebuild));
LogDelay.send();
KeyObfusc password_2 = KeyObfusc.fromPassword("password_2");
Encoder encoder_2 = new Encoder(password_2, CipherFormat.HEX);
Decoder decoder_2 = new Decoder(password_2, CipherFormat.HEX);
byte[] publicKey_2 = decoder_2.fromBytesToBytes(privateKey);
byte[] privateKey_Rebuild = encoder_2.toBytes(publicKey_2);
LogDelay.send("password_2 : " + BytesTo.stringHex(password_2.getEncoded()));
LogDelay.send("publicKey_2 : " + BytesTo.stringHex(publicKey_2));
LogDelay.send("privateKey Rebuild: " + Arrays.equals(privateKey, privateKey_Rebuild) +
" " + BytesTo.stringHex(privateKey_Rebuild));
LogDelay.send();

reading two variable values after decrypting

I am working on "Forgot Password". I am trying to create a reset token with email + current_time. email is user login whilst code will check if time >= 5 minutes then this link will not work. Here is my code:
// preparing token email + time
Date now = new Date();
String prepareToken = "?email="+email+"&tokenTime="+now.getTime();
// encrypt prepareToken value
Encryptor enc = new Encryptor();
resetToken = enc.encrypt(resetToken);
The token will be sent as for example as http://domainname.com/ForgotPassword?resetToken=adj23498ljj238809802340823
Problem:
When user click it then I got as request parameter and obviously decrypt this parameter but how can I get email in one String + time as another String
Please advise
If your issue is simply parsing the decoded String to get some sort of Map of your parameters, I'd suggest you to read Parse a URI String into Name-Value Collection .
Hope it helps.
EDIT :
Assuming you have the splitQuery(URL url) method from the previous link and that you successfully decoded the token :
public String getEmailFromToken(String decodedToken) {
// if you decoded your token it will looks like the prepareToken String
String stubUrl = "http://localhost"+decodedToken;
Map<String,String> map = splitQuery(new URL(stubUrl));
return map.get("timeToken");
}
I created a properly formed URL to respect the URL syntax.
With little tweak, you should be able to implement splitQuery for a String. I hope you can manage that.

How do I extract variable data from a line of string with tags?

I'm trying to write Java code to go to a website, read the HTML code line-by-line, extract certain pieces of data, including an embedded URL to go to another website, and repeat the process 100 times.
I've been able to isolate most of the pieces of data I need using expressions like:
s.ranking = line.substring(line.indexOf(">")+1, line.length() -7);
But I'm having problems with the following line:
<strong>Writer:</strong> Dylan <br/><strong>Producer:</strong> Tom Wilson&nbsp <br/><strong>Released:</strong> July '65, Columbia<br/>12 weeks; No. 2</p>
I need to extract and save the Writer data (Dylan). The producer data (Tom Wilson) and the Release date data (July '65). Some of the pages will have multiple writers and will be labeled "Writers:", and some will have multiple producers, labeled "Producers:"
How do I capture "Dylan" ,"Tom Wilson" and "July '65" from the above line in Java?
Thank you very much!
DM
The best approach is to use HTML parser. But as i read your comment " I'm doing this for a class and am learning about finding, isolating and extracting data."
What you can do something like :
String producer = "Producer:";
String writer = "Writer:";
String released = "Released:";
String s = "<strong>Writer:</strong> Dylan <br/><strong>Producer:</strong> Tom Wilson&nbsp <br/><strong>Released:</strong> July '65, Columbia<br/>12 weeks; No. 2</p> ";
int writerIndex = s.lastIndexOf(writer);
int producerIndex = s.lastIndexOf(producer);
int realesedIndex = s.lastIndexOf(released);
String writerExtracted = s.substring(writerIndex + writer.length(),
producerIndex).replaceAll("\\<.*?>", "");
System.out.println(writerExtracted);
String producerExtracted = s.substring(
producerIndex + producer.length(), realesedIndex).replaceAll(
"\\<.*?>", "");
System.out.println(producerExtracted);
String releasedExtracted = s.substring(
realesedIndex + released.length(), s.length()).replaceAll(
"\\<.*?>", "");
System.out.println(releasedExtracted);
Output:
Dylan
Tom Wilson&nbsp
July '65, Columbia12 weeks; No. 2
NOTE: you can get rid of signs such as &#039 or &nbsp using another regex ...

using java select city and country from a given string that contains full address

I am writing a code in which I want user to provide a string of unknown length.. suppose he provided a string.. now I want to get city and country present in that string...
If anybody have any better idea, please share..
As your requirement, you have to build a case where you need to defined all the possibility city or country like Array city= new Array["America","England","China","Myanmar"]; after that now loop your array then read the user defined line from index 0 and each time move your character point +1(do in a loop too)(convert it in String) then search your city pattern to match with the character(String). Your program complexity will increase more and more due to your requirement, I think your complexity will raise up to O(n*n), it is not good for memory.
On my view of point, you should ask from user to get the actual requirement step by step like (Enter City :_ then Enter Country :__) it is better to handle the string.GOOD LUCK!
In the question you never specified the format of the input string but assuming the format is "city, country" then this works
String s = "the name of a city, the name of a country";
String city = s.substring(0, s.indexOf(", "));
String country = s.substring(s.indexOf(", ") + 2);
System.out.println("City = " + city);
System.out.println("Country = " + country);
Well, your questions are very interesting. The program you are writing now is depending on LOGIC and I think there is no such jar files available to get solution on it. It is better to get solution manually. Did you ever think about Dictionary program. Mostly Dictionary words are written in a text file and at run time, the program load that words into an array or some other Collections. This way you can also Load Your file at runtime into a 2D array or collection(mostly HashMap is used). So you can scan your file and load it.Suppose u want to read
Example:
Agra,India
London,England
Yangon,Myanmar
Tokyo,Japan
etc...
` String line;
FileInputStream fstream = new FileInputStream(dataFile);
//dataFile is your file directory
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
HashMap<String,String> divideCityCountry =new HashMap<String,String>();
while((line=br.readLine())!=-1)
{
String[] lineSplit = line.split(",");//use the ',' as delimiter
divideCityCountry.put(lineSplit[0], lineSplit[1]);
} `
Now you can check or get the city and country in the divideCityCountry HashMap().
Hope this may helpful.Good Luck!

Parse specific output into variables Java

I am trying to find the best way how to parse specific output from jsch when connecting and executing commands on a c7000 HP enclosure.
What I have done so far is written a program that connects to a hp enclosure, executes a command, retrieves the output of the command and converts it from a stream to a String.
I end up with this String
Server Blade #1 Information:
Type: Server Blade
Manufacturer: HP
Product Name: ProLiant BL280c G6
Part Number: 507865-B21
System Board Spare Part Number: 531337-001
Serial Number: XZ73616G9Z
UUID: 38926035-5636-5D43-3330-359274423959
Server Name: SERVERONE
Asset Tag: [Unknown]
ROM Version: I25 02/01/2013
CPU 1: Intel(R) Xeon(R) CPU E5520 # 2.27GHz (4 cores)
CPU 2: Intel(R) Xeon(R) CPU E5520 # 2.27GHz (4 cores)
Memory: 49152 MB
Now I need to extract some information from this string and put it in a variable/variables. I have tried with regex but don't seem to hack it. What I need is to end up with for example, product name "Proliant BL280c G6" in a string variable that I later can use, same goes with serial number or any other info in there. What I do not need is the preceding text as Type: or Part Number:. I only need to extract what comes after that.
I am pretty new with Java, learning lots every day, can anyone here point me in the right direction of the best way of solving this?
EDIT: Thank you very much all for quick responses. I got a few ideas now on how to solve the problem. The biggest help goes to showing me how to use regex expressions correctly. What i missed there was the possibility of excluding string pieces not needed ex. (?<=Product\sName:).
String delims = "\n"; //this is the identifier of a line change in java
String[] lines = result.split(delims);
for (int i=0;i<lines.length;i++)
{
System.out.println(lines[i]);
}
This code will save (and print) the lines in that String (assuming that what you posted is saved as a java String).
You have several ways to do this thou. Sure they will be more reasonable methods to make this (regex, parsers,...), but you can do this to check if a String contains a Substring:
str1.toLowerCase().contains(str2.toLowerCase())
So, for example, if you want to know if a line of lines[i] contains the word Product Name, just make this:
subS = "Product Name";
if (lines[x].toLowerCase().contains(subS.toLowerCase()));
//x being a number between 0 and the total of lines
As stated, this is a very rustical method, but it will work.
You can use Asier's method of splitting the lines by the newline character ('\n') and then to get the value of each one you can do line.substring(line.indexOf(":")+1, line.length()). You can also get the name of the parameter with line.substring(0, line.indexOf(":")).
You could make a HashMap and access them by key:
HashMap<String, String> map = new HashMap<String, String>(); //or new HashMap<>() if you are on Java 7
String str = "your server stuff goes here";
String[] lines = str.split("\n");
for(int i = 0; i < lines.length; i++)
{
String curline = lines[i];
int index = curline.indexOf(":");
map.put(curline.substring(0, index).trim(), curline.substring(index+1, curline.length()).trim());
}
Assuming, that your response is in source.txt, we read the file
File file = new File("source.txt");
BufferedReader fileReader = new BufferedReader(new FileReader(file));
Reading line by line we match it against regexp with lookup behind:
String line;
String LOOKUP_BEHIND = "(?<=[a-zA-Z0-9 ]:)";
while((line = fileReader.readLine())!= null){
Matcher matcher1 = Pattern.compile(LOOKUP_BEHIND + ".+").matcher(line);
if (matcher1.find()){
System.out.println(matcher1.group(0));
}
}

Categories