Convert Hex String to String - android

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();
}
}

Related

What is this type of MD5?

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?

compare multiplication of JSONObjects

So, I have at this point a collections.sort of java values as you can see
and I have two keys that are integers (let's say for the sake of the example that the values of tipo are 1,2 and the values of id are 3 and 4) and I want to sort the result of theyr multiplication:
Something like this:
valA = a.get(KEY_ONE)*a.get(KEY_TWO);
valB = b.get(KEY_ONE)*b.get(KEY_TWO);
Then compare them.
How can I do it??
here is the code that I have at this point.
Collections.sort( jsonValues, new Comparator<JSONObject>() {
private static final String KEY_ONE = "tipo";
private static final String Key_TWO = "id";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_ONE.toString());
valB = (String) b.get(KEY_ONE.toString());
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
tvJson.setText(sortedJsonArray.toString());
}
}
Thanks in advance !

How to parse a CSV file

I'm trying to read a file which consists of some lines and each line has 3 parts: id , name and surname. There is also an EditText where the user needs to enter his id and in case it matches with one of the ones read from the file it should show a dialog like this one: Are you "Name", "Username"?
I've tried doing the following thing but unfortunately it doesn't work.
public String getDNI() {
String[] parts = fichero.split("\\,");
String DNI = parts[0];
return DNI;
}
public String getNombre() {
String[] parts = fichero.split("\\,");
String Nombre = parts[1];
return Nombre;
}
public String getEnunciado() {
String[] parts = fichero.split("\\,");
String Apellido = parts[2];
return Apellido;
}
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.identificacion);
Button bSiguiente = (Button) findViewById(R.id.btn_siguiente);
dniText = (EditText) findViewById(R.id.dni_candidato);
try {
InputStream is = getAssets().open(File);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i<= 100; i++) {
reader.readLine();
}
fichero = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
bSiguiente.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try{
longitud = dniText.getText().toString();
user = Integer.parseInt(dniText.getText().toString());
DNIWord(user);
for (i = 0; i<= 100; i++) {
if (longitud.equals(getDNI())){
// (longitud.length()==8){
showDialog(DIALOG_CONFIRMAR_CANDIDATO);}
else{
showDialog(DIALOG_ERROR_DNI);
}
}
}
catch (NumberFormatException e)
{}
}
A better approach is to create a class to represent your user:
class User{
public String nombre;
public String enunciado;
public String dni;
public User(String nombre, String enunciado, String dni){
this.nombre = nombre;
this.enunciado = enunciado;
this.dni = dni;
}
public User(String csvLine){
String[] values = csvLine.split(",");
this(values[0], values[1], values[2]);
}
}
I prefer the first constructor because it's easier to read.
Use like this:
ArrayList<User> users = new ArrayList<User>();
...
String s;
while ((s = reader.readLine()) != null) {
users.add(new User(s));
}
or
String s;
String[] value;
while ((s = reader.readLine()) != null) {
values = s.split(",");
users.add(new User(values[0], values[1], values[2])); <-- prefer this one
}
To make it even better:
public static final int DNI = 0;
public static final int NOMBRE = 1;
public static final int ENUNCIADO = 2;
...
String s;
String[] value;
while ((s = reader.readLine()) != null) {
values = s.split(",");
users.add(new User(values[DNI], values[NOMBRE], values[ENUNCIADO]));
}
Now you can work with your users collection using users.contains, users.getElementAt, Collections.sort, Collections.binarySearch etc.
Here is another question helpful for parsing CVS in C++: How can I read and parse CSV files in C++?
If you are open to other languages, like python, it might be much easier. For example, python has build-in csv tools:
http://docs.python.org/2/library/csv.html

Android random string generator

I have a problem.
I want to draw a random String something like this aXcFg3s2.
What i doing bad ?
How change my random()
private String random;
private String charsEntered;
private EditText et;
private Button ok;
CaptchaInterface.OnCorrectListener mCorrectListener;
public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
mCorrectListener = listener;
}
public TextCaptcha(Context context) {
super(context);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
public static String random() {
Random generator = new Random();
String x = (String) (generator.nextInt(96) + 32);
return x;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
random = random();
TextView display = (TextView) findViewById(R.id.textView1);
display.setText("Random Number: " + random); // Show the random number
et = (EditText) findViewById(R.id.etNumbers);
ok = (Button) findViewById(R.id.button1);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = et.getText().toString();
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "Bla bla bla",
Toast.LENGTH_LONG).show();
}
if (random == charsEntered) {
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}
}
the problem is that you've handled only a single character instead of using a loop.
you can create an array of characters which has all of the characters that you wish to allow to be in the random string , then in a loop take a random position from the array and add append it to a stringBuilder . in the end , convert the stringBuilder to a string.
EDIT:
here's the simple algorithm i've suggested:
private static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm";
private static String getRandomString(final int sizeOfRandomString)
{
final Random random=new Random();
final StringBuilder sb=new StringBuilder(sizeOfRandomString);
for(int i=0;i<sizeOfRandomString;++i)
sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
return sb.toString();
}
and on Kotlin:
companion object {
private val ALLOWED_CHARACTERS = "0123456789qwertyuiopasdfghjklzxcvbnm"
}
private fun getRandomString(sizeOfRandomString: Int): String {
val random = Random()
val sb = StringBuilder(sizeOfRandomString)
for (i in 0 until sizeOfRandomString)
sb.append(ALLOWED_CHARACTERS[random.nextInt(ALLOWED_CHARACTERS.length)])
return sb.toString()
}
There are a few things wrong with your code.
You cannot cast from an int to a string. Cast it to a char instead. This however will only give you a single char so instead you could generate a random number for the length of your string. Then run a for loop to generate random chars. You can define a StringBuilder as well and add the chars to that, then get your random string using the toString() method
example:
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++){
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
Also, you should use random.compareTo() rather than ==
You need to import UUID.
Here is the code
import java.util.UUID;
id = UUID.randomUUID().toString();
this is how i generate my random strings with desired characters and desired length
char[] chars1 = "ABCDEF012GHIJKL345MNOPQR678STUVWXYZ9".toCharArray();
StringBuilder sb1 = new StringBuilder();
Random random1 = new Random();
for (int i = 0; i < 6; i++)
{
char c1 = chars1[random1.nextInt(chars1.length)];
sb1.append(c1);
}
String random_string = sb1.toString();
This function run in kotlin ->
fun randomString(stringLength: Int): String {
val list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray()
var randomS = ""
for (i in 1..stringLength) {
randomS += list[getRandomNumber(0, list.size - 1)]
}
return randomS
}
fun getRandomNumber(min: Int, max: Int): Int {
return Random().nextInt((max - min) + 1) + min
}
Or you can use my library
https://github.com/Aryan-mor/Utils-Library
You can simply use the following method to generate random String with 5 character and it will return arrayList of random String
public ArrayList<String> generateRandomString() {
ArrayList<String> list = new ArrayList<>();
Random rnd = new Random();
String str = "";
String randomLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String randomLetterSmall = "abcdefghijklmnopqrstuvwxyz";
for (int n = 0; n < 50; n++) {
str = String.valueOf(randomLetters.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
//Copy above line to increase character of the String
list.add(str);
}
Collections.sort(list);
return list;
}
private fun getRandomHexString(numchars: Int): String? {
val r = Random()
val sb = StringBuffer()
while (sb.length < numchars) {
sb.append(Integer.toHexString(r.nextInt()))
}
return sb.toString().substring(0, numchars)
}
You cannot cast an int to a String. Try:
Random generator = new Random();
String x = String.valueOf (generator.nextInt(96) + 32);
final String[] Textlist = { "Text1", "Text2", "Text3"};
TextView yourTextView = (TextView)findViewById(R.id.yourTextView);
Random random = new Random();
String randomText = TextList[random.nextInt(TextList.length)];
yourTextView.setText(randomText);
Quick one liner using the org.apache.commons.lang3.RandomStringUtils package.
String randonString = RandomStringUtils.randomAlphanumeric(16);
Requires the library dependency in the gradle build file:
implementation 'org.apache.commons:commons-text:1.6'
You can simply convert current time (in millis) to string such as
import java.util.Calendar;
String newRandomId = String.valueOf(Calendar.getInstance().getTimeInMillis());
Or
String newRandomId = Calendar.getInstance().getTimeInMillis() + "";
//Eg: output: "1602791949543"

Highlighting using Regex in JSOUP for android

I am using JSoup parser to find particular parts of a html document (defined by regex) and highlight it by wrapping the found string in <span> tag. Here is my code that does the highlighting -
public String highlightRegex() {
Document doc = Jsoup.parse(htmlContent);
NodeTraversor nd = new NodeTraversor(new NodeVisitor() {
#Override
public void tail(Node node, int depth) {
if (node instanceof Element) {
Element elem = (Element) node;
StringBuffer obtainedText;
for(Element tn : elem.getElementsMatchingOwnText(pat)) {
Log.e("HELLO", tn.baseUri());
Log.e("HELLO", tn.text());
obtainedText = new StringBuffer(tn.ownText());
mat = pat.matcher(obtainedText.toString());
int nextStart = 0;
while(mat.find(nextStart)) {
obtainedText = obtainedText.replace(mat.start(), mat.end(), "<span>" + mat.group() + "</span>");
nextStart = mat.end() + 1;
}
tn.text(obtainedText.toString());
Log.e("HELLO" , "AFTER:" + tn.text());
}
}
}
#Override
public void head(Node node, int depth) {
}
});
nd.traverse(doc.body());
return doc.toString();
}
It does work but the tag <span> is visible inside the webview. What am I doing wrong?
Looks like no one knows. Here's some code that i've come up with. Slow and inefficient but works anyway. Suggestions are accepted :)
This class can be used to highlight any html using a regex.
public class Highlighter {
private String regex;
private String htmlContent;
Pattern pat;
Matcher mat;
public Highlighter(String searchString, String htmlString) {
regex = buildRegexFromQuery(searchString);
htmlContent = htmlString;
pat = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
}
public String getHighlightedHtml() {
Document doc = Jsoup.parse(htmlContent);
final List<TextNode> nodesToChange = new ArrayList<TextNode>();
NodeTraversor nd = new NodeTraversor(new NodeVisitor() {
#Override
public void tail(Node node, int depth) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
String text = textNode.getWholeText();
mat = pat.matcher(text);
if(mat.find()) {
nodesToChange.add(textNode);
}
}
}
#Override
public void head(Node node, int depth) {
}
});
nd.traverse(doc.body());
for (TextNode textNode : nodesToChange) {
Node newNode = buildElementForText(textNode);
textNode.replaceWith(newNode);
}
return doc.toString();
}
private static String buildRegexFromQuery(String queryString) {
String regex = "";
String queryToConvert = queryString;
/* Clean up query */
queryToConvert = queryToConvert.replaceAll("[\\p{Punct}]*", " ");
queryToConvert = queryToConvert.replaceAll("[\\s]*", " ");
String[] regexArray = queryString.split(" ");
regex = "(";
for(int i = 0; i < regexArray.length - 1; i++) {
String item = regexArray[i];
regex += "(\\b)" + item + "(\\b)|";
}
regex += "(\\b)" + regexArray[regexArray.length - 1] + "[a-zA-Z0-9]*?(\\b))";
return regex;
}
private Node buildElementForText(TextNode textNode) {
String text = textNode.getWholeText().trim();
ArrayList<MatchedWord> matchedWordSet = new ArrayList<MatchedWord>();
mat = pat.matcher(text);
while(mat.find()) {
matchedWordSet.add(new MatchedWord(mat.start(), mat.end()));
}
StringBuffer newText = new StringBuffer(text);
for(int i = matchedWordSet.size() - 1; i >= 0; i-- ) {
String wordToReplace = newText.substring(matchedWordSet.get(i).start, matchedWordSet.get(i).end);
wordToReplace = "<b>" + wordToReplace+ "</b>";
newText = newText.replace(matchedWordSet.get(i).start, matchedWordSet.get(i).end, wordToReplace);
}
return new DataNode(newText.toString(), textNode.baseUri());
}
class MatchedWord {
public int start;
public int end;
public MatchedWord(int start, int end) {
this.start = start;
this.end = end;
}
}
}
you have to call these two methods to get the highlighted html -
Highlighter hl = new Highlighter("abc def", htmlString);
String newhtmlString = hl.getHighlightedHtml();
This will highlight everything that matches the regex (abc)|(def)*.
You can change the way you want the regex to be built by modifying buildRegexFromQuery() function.

Categories

Resources