I have a database which is encoded with Base64. I am getting data from that DB and i use it in my android layouts, also i send data to the DB. When there is Cyrillic text, it seems that it is not encrypting it properly, because i already fixed the decoding, but it cannot recognise the cyrillic encrypted text. I am using standard function to encode it is working properly with Latin characters:
public String encrypt(String text){
String result;
result = Base64.encodeToString( text.getBytes(), Base64.NO_WRAP );
return result;}
I tried a few variations but nothing worked out. Do you know how to encrypt it correctly?
I found the answer myself:
String result = null;
try {
result = Base64.encodeToString( text.getBytes("Windows-1251"), Base64.NO_WRAP );
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks anyway :)
Related
I am using Yandex.Translate API to translate a String. It does so successfully as seen in the logcat. But when I set the EditText value (eText) to the translation result, it doesn't parse the data correctly and it shows something like {"code":200,"lang":"en-ru","text":["Он не работает!"]}, the second result instead of the first required result which is "Он не работает!"
2019-06-11 02:36:57.917 14680-
14731/com.bahraindiction.goldeneagle.sightling D/Translation Result:: Он
не работает!
2019-06-11 02:36:57.918
1468014680/com.bahraindiction.goldeneagle.sightling D/Translation Result:
{"code":200,"lang":"en-ru","text":["Он не работает!"]}
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
String translationResult = null; // Returns the translated text as a String
try {
translationResult = translatorBackgroundTask.execute(textToBeTranslated,languagePair).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Translation Result",translationResult); // Logs the result in Android Monitor
eText.setText(translationResult);
}
As seen above, Log.d displays the translated result correctly AND displays the "unparsed" translation, while eText only displays the unparsed result only.
translationResult is in JSON format, Please parse that JSON first and pick the text string and set to eText. You can use gson or similar library to parse JSON.
Whenever i am trying to encode or decode a string using UTF - 8 it is showing me Unhandled Exception: UnsupportedEncodingException.
So Android Studio is giving me two solution, which are
1) Use throws UnsupportedEncodingException
2) put that piece of code between try catch with UnsupportedEncodingException as catch argument..
So which one is good practice to use and why ?
public static String getEncodedString(String strOriginal) throws UnsupportedEncodingException {
byte[] dataFirstName = strOriginal.getBytes("UTF-8");
return Base64.encodeToString(dataFirstName, Base64.DEFAULT);
}
OR
public static String getEncodedString(String strOriginal) {
byte[] dataFirstName = new byte[0];
try {
dataFirstName = strOriginal.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Base64.encodeToString(dataFirstName, Base64.DEFAULT);
}
I would go for the second snippet, UTF-8 is one of the standard character encodings supported by every platform so the exception can actually never happen. It does not make sense to propagate it further.
If you are developing for API 19 or later, you can also use
strOriginal.getBytes(StandardCharsets.UTF_8)
which does not throw an exception.
I have an problem understanding how I am supposed to deal with emojis posted from users. I can see that the emoji is arriving to the SQLite database as an image (or font, or what?), but when selected from the database again, I get a question mark of course due to the database not understanding how it should deal with it.
Any enlightenment will do.
UPDATE
Well, utf-8 encoding/decoding was the answer just as the skilfull commenters have pointed.
My encoding:
String notes = mNotes.getText().toString();
try {
// Try to encode due to possible emojis in text
notes = URLEncoder.encode(mNotes.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException ex) {
}
arguments.putString(WorkoutDataInputFragment.TEXT_EXTRA, notes);
My decoding:
try {
// Try to decode due to possible emojis in text
mMessage.setText(URLDecoder.decode(workout.message, "utf-8"));
} catch (UnsupportedEncodingException ex) {
mMessage.setText(workout.message);
}
I post a string to a database and use this method to make sure it's URL safe:
public String URLsafe(String text){
try {
return URLEncoder.encode(text, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("URL SAFE", text+" is not URL safe");
}
return "";
}
Thing is when I retrieve the String, characters like ' look like /'. Is there a way to 'decode' the String?
Have you tried URLDecoder.decode(encoded, "utf-8")? It's the corresponding 'opposite' method to the URLEncoder.encode method you're using.
https://developer.android.com/reference/java/net/URLDecoder.html
You can use the decode method:
UrlDecoder.decode(String s, String enc)
I want to encrypt and decrypt the request and response of the web service(KSOAP or JSON) using SHA512 algorithm with private and public keys in android.
Does anyone have an idea on this. I don't have much experience on this. So please excuse me if i am wrong.
i guess the below class is used for encrypting a string. I want to know how to decrypt the string. And also i want to know how to use the private/public keys in this.
public class SHA2Demo {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String message = "test";
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
messageDigest.update(message.getBytes("UTF-16BE"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] digest = messageDigest.digest();
StringBuffer digestInHex = new StringBuffer();
for (int i = 0, l = digest.length; i < l; i++) {
// Preserve the bit representation when casting to integer.
int intRep = digest[i] & 0xFF;
// Add leading zero if value is less than 0x10.
if (intRep < 0x10) digestInHex.append('\u0030');
// Convert value to hex.
digestInHex.append(Integer.toHexString(intRep));
}
System.out.println(digestInHex.toString());
}
}
Thanks in advance.
Sha512 is a hash, not an encryption. You cannot encrypt anything with it. Use something like RSA or elliptic curves.
Sha512 is a hashing algorithm. You can NOT de-hash the response once it is hashed. That's what hash is for.
RSA or AES is what you might be looking for. Other things you may want to consider is Transport level security using SSL.