What is this type of MD5? - android

guys i have a code who hash string and object but when i hash the code online on any website encrypt its come out different from the other one in the code i want to know what is makes the other MD5 code different from this online
the md5 code:
public static String md5(String paramString){
if (Utils.isNullOrEmpty(paramString)) {
return "";
}
try
{
Object localObject1 = MessageDigest.getInstance("MD5");
if (localObject1 != null) {
((MessageDigest)localObject1).update(paramString.getBytes());
}
paramString = ((MessageDigest)localObject1).digest();
localObject1 = new StringBuilder();
int j = paramString.length;
int i = 0;
while (i < j)
{
String str = Integer.toHexString(paramString[i] & 0xFF);
if (str.length() == 1) {
((StringBuilder)localObject1).append('0');
}
((StringBuilder)localObject1).append(str);
i += 1;
}
}
catch (NoSuchAlgorithmException localNoSuchAlgorithmException)
{
Object localObject2;
for (;;)
{
localNoSuchAlgorithmException.printStackTrace();
localObject2 = null;
}
return ((StringBuilder)localObject2).toString();
}
he take two value
public static String generateChkSum(HashMap<String, Object> paramHashMap) {
paramHashMap = a(paramHashMap);
Log.d("CheckSum Before Concat :::::::::: ", paramHashMap);
paramHashMap = md5(paramHashMap);
paramHashMap = md5(paramHashMap + "^" + AppConstants.a);
Log.d("CheckSum After Concat :::::::::: ", paramHashMap);
return paramHashMap;
the logcat:
01-27 02:25:08.440 2369-3661/com.test.app D/CheckSum Before Concat ::::::::::: kinghema^1784e7fe94d4750df3af902489489b77
01-27 02:25:08.440 2369-3661/com.test.app D/CheckSum After Concat  ::::::::::: 781973a6c9d36f18d9f02f80dc2e5d6e
and the result is :781973a6c9d36f18d9f02f80dc2e5d6e
but if we take the 2 value and hash them online normally:
39cec39f604f5a4380bae1f00c7404b6
so my question is what is this type of hashing he use? whats is the difference between this code and the online code what is the method he use?

Related

Arduino can't find substring in string in received serial text from device

I am setting up a send GPS position from an Android to and Arduino so that the Arduino will follow the Android phone. I get a string from the Android and I seem to get it correctly and get the proper length but I can't find the identifier ("Lon" or "Lat") from the string.
I get the a string from the Android, I put the array of received bytes into an array, I converted the array to a string and I tested it to check if it is a string and I checked the length of the string and it all appears to be legit but I can't identify if my identifier is in the string to extract the data.
#include <SoftwareSerial.h>
// Example 2 - Receive with an end-marker
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
String mlong;
String mlat;
long mlong_val;
long mlat_val;
String temp_mlat_val;
String temp_mlong_val;
String temp_str;
boolean newData = false;
SoftwareSerial BT_Serial(10, 11);
void setup() {
Serial.begin(9600);
Serial.println("Bluetooth receive 003");
BT_Serial.begin(9600);
}
void loop() {
recvWithEndMarker();
showNewData();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (BT_Serial.available() > 0 && newData == false) {
rc = BT_Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
String temp_str = receivedChars;
Serial.print("This is the string, I hope ");
Serial.println(temp_str);
unsigned int lastStringLength = temp_str.length();
Serial.print("This is the length of the string, I hope ");
Serial.println(lastStringLength);
if (temp_str.substring(lastStringLength) == "Lat"){
Serial.println("Lat");
}
else {Serial.println("After looking for Lat, not found");
}
newData = false;
}
}
void loop() {
// Set up a String:
String stringOne = "Content-Type: text/html";
Serial.println(stringOne);
// substring(index) looks for the substring from the index position to the end:
if (stringOne.substring(19) == "html") {
Serial.println("It's an html file");
}
// you can also look for a substring in the middle of a string:
if (stringOne.substring(14, 18) == "text") {
Serial.println("It's a text-based file");
}
tried this replacing their string with my string in my code
if (newData == true) {
Serial.print("This just in ... ");
temp_str = "Lat12.34567";
Serial.print("This is the string, I hope ");
Serial.println(temp_str);
unsigned int lastStringLength = temp_str.length();
Serial.print("This is the length of the string, I hope ");
Serial.println(lastStringLength);
if (temp_str.substring(lastStringLength) == "Lat"){
Serial.println("Lat");
}
else {Serial.println("After looking for Lat, not found");
}
newData = false;
and it doesn't work with just the string, not from the Android
Expect to just print "Lat" if the identifier "Lat" was located in the string, it doesn't print

Apply a filter on FirebaseRecyclerAdapter

I am using FirebaseRecyclerAdapter to display chat messages.
private void attachRecyclerViewAdapter() {
lastFifty = mChatRef.limitToLast(50).;
mRecyclerViewAdapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(
Chat.class, R.layout.message, ChatHolder.class, lastFifty) {
#Override
public void populateViewHolder(ChatHolder chatView, Chat chat, int position) {
chatView.setName(chat.getName());
chatView.setText(chat.getText());
chatView.setTimeLocation(chat.getTime());
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null && chat.getUid().equals(currentUser.getUid())) {
chatView.setIsSender(true);
} else {
chatView.setIsSender(false);
}
}
};
I have a list that contains list of specific users. I would like to apply filter to see only messages from those specific users. What should I do ?
You can create messages with user id pair nodes. For example messages->'uid1-uid2'->...
To prevent which is first order uids alphatecially as the following messageId generator code does:
public static String getMessageId(String id1, String id2){
String messageId;
if(id1.compareTo(id2) < 0){
messageId = id1 + "-" + id2;
}else if(id1.compareTo(id2) > 0) {
messageId = id2 + "-" + id1;
}else{
messageId = id1;
}
return messageId;
}
When you want to see the chat history between a user and urself, obtain the user's id and generate messageId = getMessageId(id1, id2); or messageId = getMessageId(id2, id1); gives the same result since the order doesn't affect the result.
Then call the messages from the node messages -> messageId
P.S. you should restructure your messages node as i describe.
EDIT
You can convert messageId to md5 equivalent to save chars.
just change
return messageId;
to
return md5(messageId);
where md5 is:
public static String md5(final String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest
.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}

Convert Hex String to String

HI I have to tried multiple ways to convert Hex String to ASCII String but not getting success. While before I have done the same but now I am not able to achieve it.
My Code is
private static String hexToASCII(String hexValue)
{
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexValue.length(); i += 2)
{
String str = hexValue.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
}
return output.toString();
}
but it is returning garbage value like b��¡
and my Hex String is
621c8002008a820101a10a8c0341c2009c0341c2008302010288008a0105
Please help me if someone has also suffered from the same issue and fixed it.
Thanks ....
Try this out
public class HextoAsscii {
public static void main(String args[])
{
String hex="621c8002008a820101a10a8c0341c2009c0341c2008302010288008a0105";
String str="";
str= hexToASCII(hex);
}
private static String hexToASCII(String hexValue)
{
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexValue.length(); i += 2)
{
if(i+2<=hexValue.length())
{
String str = hexValue.substring(i, i + 2);
output.append(Integer.parseInt(str, 16));
}
}
System.out.println(output.toString());
return output.toString();
}
}

Compare contents of two files line by line

public class MainActivity extends Activity {
FileOutputStream fos;
FileInputStream fOne, fTwo;
ArrayList<String> arr1 = new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
ArrayList<String> wordsTwo = new ArrayList<String>();
int count = 0;
int countTwo = 0;
int countThree = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fileOne = (Button)findViewById(R.id.file1);
Button fileTwo = (Button)findViewById(R.id.file2);
Button compare = (Button)findViewById(R.id.compare);
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr1.add("4");
//arr1.add("3");
arr2.add("1");
arr2.add("2");
fileOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File1", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr1.size(); temp++)
{
fos.write((arr1.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
fileTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File2", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr2.size(); temp++)
{
fos.write((arr2.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
compare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fOne = openFileInput("File1");
fTwo = openFileInput("File2");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanFile = new Scanner(new DataInputStream(fOne));
Scanner scanFileT = new Scanner(new DataInputStream(fTwo));
words = new ArrayList<String>();
wordsTwo = new ArrayList<String>();
while (scanFile.hasNextLine())
{
if(scanFile.nextLine()!=null)
{
count++;
}
while(scanFileT.hasNextLine())
{
if(scanFileT.nextLine()!=null)
{
countTwo++;
}
}
}
try
{
fOne.close();
fTwo.close();
scanFile.close();
scanFileT.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "One : " + count, 1000).show();
Toast.makeText(getBaseContext(), "Two : " + countTwo, 1000).show();
Toast.makeText(getBaseContext(), "Three : " + countThree, 1000).show();
count = 0 ;
countTwo = 0;
countThree = 0;
}
});
}
}
Above is the code to write and read the file. What I did here, write two files and read the contents..Now I have to compare contents of files line by line. What needs to be done?
Try following code. This will give you desired output. I took files from asset directory. So you need to replace that line of code if you are taking files from other directory.
private void compareFiles() throws Exception {
String s1 = "";
String s2 = "", s3 = "", s4 = "";
String y = "", z = "";
// Reading the contents of the files
BufferedReader br = new BufferedReader(new InputStreamReader(
getAssets().open("first.txt")));
BufferedReader br1 = new BufferedReader(new InputStreamReader(
getAssets().open("second.txt")));
while ((z = br1.readLine()) != null) {
s3 += z;
s3 += System.getProperty("line.separator");
}
while ((y = br.readLine()) != null) {
s1 += y;
s1 += System.getProperty("line.separator");
}
// String tokenizing
StringTokenizer st = new StringTokenizer(s1);
String[] a = new String[10000];
for (int l = 0; l < 10000; l++) {
a[l] = "";
}
int i = 0;
while (st.hasMoreTokens()) {
s2 = st.nextToken();
a[i] = s2;
i++;
}
StringTokenizer st1 = new StringTokenizer(s3);
String[] b = new String[10000];
for (int k = 0; k < 10000; k++) {
b[k] = "";
}
int j = 0;
while (st1.hasMoreTokens()) {
s4 = st1.nextToken();
b[j] = s4;
j++;
}
// comparing the contents of the files and printing the differences, if
// any.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
}
}
Log.d("Home", "No. of differences : " + x);
if (x > 0) {
Log.d("Home", "Files are not equal");
} else {
Log.d("Home", "Files are equal. No difference found");
}
}
Input File 1
Hi
Hello
Chintan
Rathod
Input File 2
Hi
HellO
Chintan
RathoD
Output
08-26 12:07:58.219: DEBUG/Home(2350): Hello3. -- HellO3.
08-26 12:07:58.219: DEBUG/Home(2350): Rathod -- RathoD
08-26 12:07:58.229: DEBUG/Home(2350): No. of differences : 2
08-26 12:07:58.229: DEBUG/Home(2350): Files are not equal
Edit
To get Difference between two files
Use StringUtils library which is provide by Apache and check this Documentation for more about that library.
And modify following lines of code.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
//to print difference
if (a[m].length() < b[m].length())
Log.d("Home", "" + StringUtils.difference(a[m], b[m]));
else
Log.d("Home", "" + StringUtils.difference(b[m], a[m]));
}
}
Output
08-26 17:51:26.949: DEBUG/Home(17900): 12 -- 123
08-26 17:51:26.949: DEBUG/Home(17900): Difference String : 3
08-26 17:51:26.949: DEBUG/Home(17900): No. of differences : 1
08-26 17:51:26.949: DEBUG/Home(17900): Files are not equal
Try using java.util.Scanner
while (sc1.hasNext() && sc2.hasNext()) {
String str1 = sc1.next();
String str2 = sc2.next();
if (!str1.equals(str2))
System.out.println(str1 + " != " + str2);
}
Change your while loop to the following:
while (scanFile.hasNextLine() && scanFileT.hasNextLine())
{
if(scanFileT.nextLine().equals(scanFile.nextLine()))
{
// The lines are equal.
} else {
// The lines are not equal.
}
}
if(scanFile.hasNextLine() || scanFileT.hasNextLine())
{
// If more lines remain in one of the files, they are not equal.
} else {
// If no content remains in both files, they are equal.
}
Depending on the size of your file, I would recommend some optimisation like checking the file sizes before you go through them line by line.
The overall logic reads as follows; if both have another line, compare it to see if it is equal. If they don't have another line, check if one of them has lines remaining, if so, they are not equal.
Update
After clarifying the objective of the comparison in chat, see the comments to this question, I have come to the conclusion that another comparison would be more effective and, as a matter of fact, correct. The comparison algorithm above works great if comparing the structure of text but not if comparing a data vector which may or may not be sorted. After some discussion, we came to the conclusion that data needs to be sorted or the comparison will blow the complexity to at least O(n^2)which could be done in O(2n) if the data is sorted. Here the algorithm's skeleton:
if(! scanGroupFriends.hasNextLine())
{
//simple sanity check to see if we need to compare at all. In this case, add all friends.
} else {
String nextFriend = scanGroupFriends.nextLine();
while(scanAllFriends.hasNextLine())
{
if(scanAllFriends.nextLine().equals(nextFriend))
{
// Friend already figures, do not add him and advance the list of group friends.
if(scanGroupFriends.hasNextLine())
{
nextFriend = scanGroupFriends.nextLine();
} else {
// There are no more friends in the group, add all remaining friends to list to show.
break; // Terminate the `while` loop.
}
}
}
}
However, I personally think it is bad to make to many assumptions. What I would suggest is that the friends be saved in a Set, a TreeSet for example. Then, serialize the object rather than manually writing it to file. Sets are neat because they hold several interesting objects. For example, you could easily use the following code to remove all friends in a group from the set of all friends:
allFriends.removeAll(groupFriends);
However, be aware that this removes it from the set completely so you should make a copy beforehand.

regular-expressions android

i have string like these for example
309\306\308\337_338
309\306\337_338
310
311\315_316\336_337
311\315_316\336_337
311\335_336
these strings means list of page number , for example string "309\306\308\337_339" means
pages 309,306,308,337,338,339
i want to pass one of these string to function which return it as string like this
309,306,308,337,338,339
this function do that but in c# , i want to impalement in android
private static string Get_PageNumbers(string str)
{
ArrayList arrAll = new ArrayList();
MatchCollection match;
string[] excar;
string strid, firstNumber, lastlNumber;
int fn, ln;
ArrayList arrID = new ArrayList();
//***In Case The Range Number Between "_"
if (str.Contains("_"))
{
// match_reg = new Regex("(w?[\\d]+)*(_[\\d]+)");
Regex matchReg = new Regex("(w?[\\69]+_[\\d]+)*(q?[\\d]+//)*(a?[\\d]+_[\\d]+)*(y?[\\d]+)*");
match = matchReg.Matches(str);
int count = match.Count;
excar = new string[0];
for (int i = 0; i < count; i++)
{
Array.Resize(ref excar, count);
excar[i] = match[i].Groups[0].Value;
if (excar[i] != string.Empty)
arrID.Add(excar[i]);
}
//******IF Array Contains Range Of Number Like"102_110"
if (str.Contains("_"))
{
for (int i = 0; i < arrID.Count; i++)
{
strid = arrID[i].ToString();
if (arrID[i].ToString().Contains("_"))
{
int idy = strid.LastIndexOf("_");
firstNumber = strid.Substring(0, idy);
if (idy != -1)
{
lastlNumber = strid.Substring(idy + 1);
fn = int.Parse(firstNumber);
arrAll.Add(fn);
ln = int.Parse(lastlNumber);
for (int c = fn; c < ln; c++)
{
fn++;
arrAll.Add(fn);
}
}
}
else
{
arrAll.Add(arrID[i].ToString());
}
}
//******If Array Contain More Than One Number
if (arrAll.Count > 0)
{
str = "";
for (int i = 0; i < arrAll.Count; i++)
{
if (str != string.Empty)
str = str + "," + arrAll[i];
else
str = arrAll[i].ToString();
}
}
}
}
//***If string Contains between "/" only without "_"
else if (str.Contains("/") && !str.Contains("_"))
{
str = str.Replace("/", ",");
}
else if (str.Contains("\\"))
{
str = str.Replace("\\", ",");
}
return str;
}
I think this is easier to do with split function:
public static String Get_PageNumbers(String str) {// Assume str = "309\\306\\308\\337_338"
String result = "";
String[] pages = str.split("\\\\"); // now we have pages = {"309","306","308","337_338"}
for (int i = 0; i < pages.length; i++) {
String page = pages[i];
int index = page.indexOf('_');
if (index != -1) { // special case i.e. "337_338", index = 3
int start = Integer.parseInt(page.substring(0, index)); // start = 337
int end = Integer.parseInt(page.substring(index + 1)); // end = 338
for (int j = start; j <= end; j++) {
result += String.valueOf(j);
if (j != end) { // don't add ',' after last one
result += ",";
}
}
} else { // regular case i.e. "309","306","308"
result += page;
}
if (i != (pages.length-1)) { // don't add ',' after last one
result += ",";
}
}
return result; // result = "309,306,308,337,338"
}
For example this function when called as follows:
String result1 = Get_PageNumbers("309\\306\\308\\337_338");
String result2 = Get_PageNumbers("311\\315_316\\336_337");
String result3 = Get_PageNumbers("310");
Returns:
309,306,308,337,338
311,315,316,336,337
310
if i can suggest different implementation....
first, split string with "\" str.split("\\");, here you receive an array string with single number or a pattern like "num_num"
for all string founded, if string NOT contains "" char, put string in another array (othArr named), than, you split again with "" str.split("_");, now you have a 2 position array
convert that 2 strings in integer
now create a loot to min val form max val or two strings converted (and put it into othArr)
tranform othArr in a string separated with ","

Categories

Resources