android:exception in encryption - android

I am making an app in which i have to encrypt the data and send it to server and in that case while converting data to int form i am getting number format exception .My code is as follows:
public String encryptData(String key, String s)
{
try{
System.out.println("encrypt");
// byte[] utf8 = data.getBytes("UTF8");
byte[] fin=s.getBytes();
System.out.println("encrypt2");
// byte[] enc = ecipher.doFinal(fin);
System.out.println("encrypt3");
}catch (Exception e) {
System.out.println(e);
}
System.out.println("1");
int keyLen = key.length();
// int dataLen = Convert.ToInt16(data.length());
System.out.println("2");
Integer dataLen=Integer.parseInt(s); // **This line is giving exception**
System.out.println("3");
char chData;
char chKey;
char[] data1 = s.toCharArray();
char[] key1 = key.toCharArray();
System.out.println("4");
StringBuilder encryptedData = new StringBuilder();
for (int i = 0; i < dataLen; i++)
{
chData = data1[i];
for (int j = 0; j < keyLen; j++)
{
chKey = key1[j];
chData = (char)(chData ^ chKey);
}
encryptedData.append(chData);
}
return (encryptedData.toString());
}
and My xml is :
xml="<?xml version='1.0' encoding='utf-8'?>" + "<admin_auth_req><user_name>" +username+ "</user_name>" + "<password>" +PWOrd+ "</password></admin_auth_req>";
Exception is:
java.lang.NumberFormatException: unable to parse '<?xml version='1.0' encoding='utf-8'?><admin_auth_req><user_name>newuser</user_name><password>tester</password></admin_auth_req>' as integer
`

You are triying to convert a String value which is not a number representation into String. What you really should do is to find the length of the String. So change this line:
Integer dataLen=Integer.parseInt(s);
to:
int dataLen = s.length();

You are trying to parse this string as Integer???
<?xml version='1.0' encoding='utf-8'?><admin_auth_req><user_name>newuser</user_name><password>tester</password></admin_auth_req>
What did you expect?

Related

How to write a hash function in Android similar to the Python function?

I am currently developing a distributed system application. I want to verify a Python generated hash in the Android application. I have a python method to do hashing in given string variables.
This is the python function and it works well.
hash_value = hashlib.sha1("PARAMETER123".encode("UTF-8")).hexdigest()
I want to implement the same function in my Android application. I hope some expert can help as soon as possible.
You can try the following code snippet,
String text = "PARAMETER123";
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] textBytes = text.getBytes("UTF-8");
md.update(textBytes, 0, textBytes.length);
byte[] sha1hash = md.digest();
String encrypted_text = = convertToHex(sha1hash);
and the convertToHex() method
private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (byte b : data) {
int halfbyte = (b >>> 4) & 0x0F;
int two_halfs = 0;
do {
buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
halfbyte = b & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
This will convert a UTF-8 based text into a SHA1 hex.
Reference: https://stackoverflow.com/a/5980789/2506025
Here is a simple SHA1 method for Java:
String sha1Hash( String toHash )
{
String hash = null;
try
{
MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
byte[] bytes = toHash.getBytes("UTF-8");
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
// This is ~55x faster than looping and String.formating()
hash = bytesToHex( bytes );
}
catch( NoSuchAlgorithmException e )
{
e.printStackTrace();
}
catch( UnsupportedEncodingException e )
{
e.printStackTrace();
}
return hash;
}
// http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex( byte[] bytes )
{
char[] hexChars = new char[ bytes.length * 2 ];
for( int j = 0; j < bytes.length; j++ )
{
int v = bytes[ j ] & 0xFF;
hexChars[ j * 2 ] = hexArray[ v >>> 4 ];
hexChars[ j * 2 + 1 ] = hexArray[ v & 0x0F ];
}
return new String( hexChars );
}
You can include those methods and call sha1hash.

Having trouble when trying to md5 a string in android

On Android, I get the following error when I try to md5 a string:
"Performing stop of activity that is not resumed"
I need to attach the md5 to a URL.
Please help
//md5 code
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(text.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
}
//request code
encryptedTaskId = MDConversion.MD5(taskId);
Log.v("inside doInBackground :: ", "inside doInBackground :: ");
totalUrl = baseUrl + "&access_token=" + accessToken + "&id=" + encryptedTaskId;
Log.v("fetch users to forward task url :: ", "url :: "+totalUrl);
HttpGet get = new HttpGet(totalUrl);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
response = client.execute(get);
Try to use this static function:
public static final String md5(final String toEncrypt) {
try {
final MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(toEncrypt.getBytes());
final byte[] bytes = digest.digest();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02X", bytes[i]));
}
return sb.toString().toLowerCase();
} catch (Exception exc) {
return ""; // Impossibru!
}
}

How to covert String to byte for BLE mBluetoothGatt.writeCharacteristic?

I am developing in Android BLE.
I try to send string to BLE device(like TI CC2541) , and it seems can not send string direct to BLE device.
It need to convert the String to Byte.
I have search some information , there has someone use URLEncoder.encode.
But I am not sure which is the answer what I need.
But how to convert the String to Byte?
The following code is writeCharacteristic for BLE
public void writeString(String text) {
// TODO Auto-generated method stub
BluetoothGattService HelloService = mBluetoothGatt.getService(HELLO_SERVICE_UUID);
BluetoothGattCharacteristic StringCharacteristic = HelloService.getCharacteristic(UUID_HELLO_CHARACTERISTIC_WRITE_STRING);
mBluetoothGatt.setCharacteristicNotification(StringCharacteristic , true);
int A = Integer.parseInt(text);
//How to convert the String to Byte here and set the Byte to setValue ?????
StringCharacteristic .setValue(A, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
mBluetoothGatt.writeCharacteristic(StringCharacteristic );
Log.d(TAG, "StepCount Characteristic End!");
}
How to convert the String to Byte?
Where you get your String:
byte[] strBytes = text.getBytes();
byte[] bytes = context.yourmWriteCharacteristic.getValue();
Please add a null check too like:
if (bytes == null) {
Log.w("Cannot get Values from mWriteCharacteristic.");
dismiss();// equivalent action
}
if (bytes.length <= strBytes.length) {
for(int i = 0; i < bytes.length; i++) {
bytes[i] = strBytes[i];
}
} else {
for (int i = 0; i < strBytes.length; i++) {
bytes[i] = strBytes[i];
}
}
Now, something like:
StepCount_Characteristic.setValue(bytes);
mBluetoothGatt.writeCharacteristic(StepCount_Characteristic);
I found the following code help me convert the string.
private byte[] parseHex(String hexString) {
hexString = hexString.replaceAll("\\s", "").toUpperCase();
String filtered = new String();
for(int i = 0; i != hexString.length(); ++i) {
if (hexVal(hexString.charAt(i)) != -1)
filtered += hexString.charAt(i);
}
if (filtered.length() % 2 != 0) {
char last = filtered.charAt(filtered.length() - 1);
filtered = filtered.substring(0, filtered.length() - 1) + '0' + last;
}
return hexStringToByteArray(filtered);
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
private int hexVal(char ch) {
return Character.digit(ch, 16);
}
If you want to convert string value. you just need to call like the following:
String text;
byte[] value = parseHex(text);

Unable to replace in my android app

android version:4.2
my sample code is:
try {
//HttpResponse response = httpClient.execute(httpGet, localContext);
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
text=text.replaceAll("<", "<").replace(">", ">").replace(" ", " ");
int start=text.indexOf("<message>");
start=start+9;
int end=text.indexOf("</message>");
text=text.substring(start, end);
JSONArray ja = new JSONArray(text) ;
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < 1; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
title+= jo.getString("Title")+",";
url= jo.getString("URL");
desc= jo.getString("Description");
}
} catch (Exception e) {
return e.getLocalizedMessage();
}
issue: Varible desc(i.e., description in my json)contains ** ** in its contents.I have converted HTML into string in android using following code:
Spanned marked_up = Html.fromHtml(results);
tv2.setText(marked_up.toString(),BufferType.SPANNABLE);
Still it is not replacing ** **.
Help me anyone plz.
ThankYou in advance.
marked_up.toString().replaceAll("&nbsp","");
Use tv2.setText(marked_up) instead of tv2.setText(marked_up.toString(),BufferType.SPANNABLE);
public static final String unescapeHTML(String s, int f){
String [][] escape = {{ " " , " " }};
int i, j, k;
i = s.indexOf("&", f);
if (i > -1) {
j = s.indexOf(";" ,i);
f = i + 1;
if (j > i) {
String temp = s.substring(i , j + 1);
k = 0;
while (k < escape.length) {
if (escape[k][0].equals(temp)) break;
else k++;
}
if (k < escape.length) {
s = s.substring(0 , i) + escape[k][1] + s.substring(j + 1);
return unescapeHTML(s, f);
}
}
}
return s;
}
Use this function as text = unescapeHTML(text,0);
Try to change following line desc= jo.getString("Description"); into this:
desc= Html.fromHtml(jo.getString("Description"));
Use this method,
Html.fromHtml(text);
title+= Html.fromHtml(jo.getString("Title"))+",";
i think you should have to remove &nbsp,<,> from server side because you have to check different node every time.... so change on server side code of webservice... it will be best for you...

Android from string to string array

hi to all i have this code have this code which reads a some text and it extracts any strings between the '[' and ']' and it should print it on the screen
String lines[] = {addressString};
for (int i = 0; i < lines.length; i++) {
int be = lines[i].indexOf('[');
int e = lines[i].indexOf(']');
String fields = lines[i].substring(be+1, e);
}
my question is that i want to change the string "fields" to an array string so when i print it
i can print it as fields[0],fields[1],....etc until the end of the text....?
any suggestions...??
Thanks a lot
Is this what you mean?
String lines[] = {addressString};
String fields[] = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
int be = lines[i].indexOf('[');
int e = lines[i].indexOf(']');
fields[i] = lines[i].substring(be+1, e);
}

Categories

Resources