Import and consume javascript in android activity - javascript

I am trying to establish a connection between android app and webservice. I am sending the encrypted username and password using AES encryption. But my encrypted username and password do not match with the webservice and responses as false.
Same thing I am doing in website encrypting credential with AES encryption in javascript and validating user with webservice everything works fine. I checked AES output for android defers from javascript output.
Bellow code is used in android to encrypt username and password
public class RijndaelCrypt {
public static final String TAG = "EncryptLog2";
private static String TRANSFORMATION = "AES/CBC/PKCS7Padding";
private static String ALGORITHM = "AES";
private static String DIGEST = "MD5";
private static Cipher _cipher;
private static SecretKey skeySpec;
private static IvParameterSpec _IVParamSpec;
//16-byte private key
private static byte[] IV = MainActivity.key.substring(0,16).getBytes();
/**
* Constructor
*
* #password Public key
*/
public RijndaelCrypt(String password) {
try {
//Encode digest
MessageDigest digest;
digest = MessageDigest.getInstance(DIGEST);
skeySpec = new SecretKeySpec(digest.digest(password.getBytes()), ALGORITHM);
//Initialize objects
_cipher = Cipher.getInstance(TRANSFORMATION);
_IVParamSpec = new IvParameterSpec(IV);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "No such algorithm " + ALGORITHM, e);
} catch (NoSuchPaddingException e) {
Log.e(TAG, "No such padding PKCS7", e);
}
}
/**
* Encryptor.
*
* #return Base64 encrypted text
* #text String to be encrypted
*/
public String encrypt(byte[] text) {
byte[] encryptedData;
try {
_cipher.init(Cipher.ENCRYPT_MODE, skeySpec, _IVParamSpec);
encryptedData = _cipher.doFinal(text);
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key (invalid encoding, wrong length, uninitialized, etc).", e);
return null;
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, "Invalid or inappropriate algorithm parameters for " + ALGORITHM, e);
return null;
} catch (IllegalBlockSizeException e) {
Log.e(TAG, "The length of data provided to a block cipher is incorrect", e);
return null;
} catch (BadPaddingException e) {
Log.e(TAG, "The input data but the data is not padded properly.", e);
return null;
}
return Base64.encodeToString(encryptedData, Base64.DEFAULT);
}
/**
* Decryptor.
*
* #return decrypted text
* #text Base64 string to be decrypted
*/
public String decrypt(String text) {
try {
_cipher.init(Cipher.DECRYPT_MODE, skeySpec, _IVParamSpec);
byte[] decodedValue = Base64.decode(text.getBytes(), Base64.DEFAULT);
byte[] decryptedVal = _cipher.doFinal(decodedValue);
return new String(decryptedVal);
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key (invalid encoding, wrong length, uninitialized, etc).", e);
return null;
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, "Invalid or inappropriate algorithm parameters for " + ALGORITHM, e);
return null;
} catch (IllegalBlockSizeException e) {
Log.e(TAG, "The length of data provided to a block cipher is incorrect", e);
return null;
} catch (BadPaddingException e) {
Log.e(TAG, "The input data but the data is not padded properly.", e);
return null;
}
}
}
Can i use that javascript in android without WebView.
Note: webservice is built in .net c#.
Sorry for any grammatical mistake, This is my 1st question on StackOverflow.

Related

Android Capacitor JS Plugin does not reply

I am working on a java plugin that is supposed to recieve some info from a js vue3 program and then do a URL post operation, and then return some of the info found back to the js code. I am using capacitor and android. This is my error message:
2022-08-22 13:46:23.773 27544-27544/org.theguy.GptEtc E/Capacitor/Console: File: http://localhost/js/app.6577adf2.js - Line 1 - Msg: Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
I think this means that something other than valid JSON is being delivered to the js code. I know that the app is delivering info to the java android class. This is some of my java code.
#CapacitorPlugin(name = "URLPOST")
public class PluginURLPost extends Plugin {
#PluginMethod()
public void post(PluginCall call) {
String post_url = call.getString("post_url", "");
String bearer = call.getString("bearer", "pipeline_");
JSObject ret = new JSObject();
try {
String value = this.doPost(post_url, bearer);
System.out.println("value " + value);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(value));
ResultPreview preview = gson.fromJson(reader, ResultPreview.class);
String val = preview.getResult_preview()[0][0];
val = "result string here."; // <-- add this for easy testing
ret.put("response_text", val.replace("\n", "\\n"));
System.out.println("response here: " + val);
}
catch (Exception e) {
e.printStackTrace();
}
//call.setKeepAlive(true);
call.resolve(ret);
}
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
String doPost(String post_url, String bearer ) throws IOException {
// ... do some post request here ...
return response_body;
}
}
class ResultPreview {
#SerializedName("result_preview")
String [][] result_preview ;
public void setResult_preview(String[][] result) {
this.result_preview = result;
}
public String[][] getResult_preview() {
return this.result_preview;
}
}
This is some of my js code.
import { registerPlugin } from "#capacitor/core";
const URLPOST = registerPlugin("URLPOST");
const request = {
"line": line,
"pipeline_model": details[engine]["app_model"].trim(),
"bearer": details[engine]["api_key"].trim(),
"post_url": details[engine]["url"].trim(),
"length": 25,
"top_k": 50
};
console.log("request", request);
var {response_text} = await URLPOST.post(request);
console.log("response_text 1",response_text);
I don't know what to do.
I tried this, and things work better. I don't know if this is the ultimate solution.
#PluginMethod()
public void post(PluginCall call) {
bridge.saveCall(call); // <-- add this
call.release(bridge); // <-- add this
String pipeline_model = call.getString("pipeline_model", "pipeline_");
String post_url = call.getString("post_url", "");
JSObject ret = new JSObject();
try {
String value = this.doPost(post_url);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(value));
ResultPreview preview = gson.fromJson(reader, ResultPreview.class);
String val = preview.getResult_preview()[0][0];
ret.put("response_text", val.replace("\n", "\\n"));
System.out.println("response here: " + val);
}
catch (Exception e) {
e.printStackTrace();
}
call.resolve(ret);
}
This is not found on the capacitor site, but instead I found it digging around the internet.

Encrypt Javascript - Decrypt Java

I want to encrypt the password before to submit.
app.js
function encryptPass() {
var encrypted = CryptoJS.AES.encrypt("Test", "1234").toString();
$("#password").val(encrypted)
}
After to submit, the tool call method: decrypt
pass.java
public static String decrypt(String strToDecrypt) {
def result
try {
if (strToDecrypt) {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, obtenerSecretKey());
result = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)))
}
} catch (Exception e) {
println e
throw e;
} finally {
return result
}
}
private static SecretKeySpec obtenerSecretKey () {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
def semilla = "1234"
def key = sha.digest(semilla.getBytes("UTF-8"));
key = Arrays.copyOf(key, 16);
return new SecretKeySpec(key, "AES");
}
I'm getting this error:
javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
Any suggestions or other encrypt type?

Httpurlconnection parameter with space

I am trying to use httpurlconnection to post parameters to URL. The httpurlconnection seems to be posting fine when posting values without spaces however the issue appears when something like submit=Login Accountwhich contains a space. I have tried to use a plus symbol and %20 instead of the space however I have been unsuccessful submitting the form.
String requestParameters =“password=test123&confirm=test123&id=2869483&submit=Login Account”;
posting function
public static String postURL(String urlString, String parameters, int timeout, Proxy proxy, String accept, String acceptEncoding, String userAgent, String acceptLanguage) throws IOException {
URL address = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) address.openConnection(proxy);
httpConnection.setRequestMethod("POST");
httpConnection.addRequestProperty("Accept", accept);
httpConnection.addRequestProperty("Accept-Encoding", acceptEncoding);
httpConnection.addRequestProperty("User-Agent", userAgent);
httpConnection.addRequestProperty("Accept-Language", acceptLanguage);
httpConnection.addRequestProperty("Connection", "keep-alive");
httpConnection.setDoOutput(true);
httpConnection.setConnectTimeout(timeout);
httpConnection.setReadTimeout(timeout);
DataOutputStream wr = new DataOutputStream(httpConnection.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
httpConnection.disconnect();
BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
String result = response.toString();
in.close();
return result;
}
request to post using posting function
*
ArrayList<unlock> ns = new ArrayList<>();
try {
ns = methods.UnlockRequest("register#test.com");// gets urls from database.
} catch (IOException e) {
e.printStackTrace();
}
String s = ns.get(0).toString(); // gets first url in list
url=s; // sets url to s
String[] st= url.split("id="); // splits url to get id
System.out.println(url);
System.out.println(st[1]);
System.out.println("accounts class reached");
String requestParameters = null;
requestParameters = "password=test123&confirm=test123&id=2869483&submit=Login Account”;
System.out.println(requestParameters);
ConnectionSettings connectionSettings = Variables.get().getConnectionSettings();
String creation = "";
System.out.println(Variables.get().getCaptchaSolution());
try {
if (connectionSettings.isProxyCreation()) {
creation = HTTPRequests.postURL(url, requestParameters, 30000, connectionSettings.getProxy(), connectionSettings.getAcceptCriteria(), connectionSettings.getAcceptEncoding(),
connectionSettings.getUserAgent(), connectionSettings.getAcceptLanguage());
}
} catch (FileNotFoundException e) {
System.out.println(ColoredText.criticalMessage("Error: Your IP is banned from requesting. Ending script."));
Variables.get().setStopScript(true);
} catch (IOException e) {
e.printStackTrace();
Variables.get().setStopScript(true);
}
*

Generate HMAC SHA Algorithm using URI and Key

I wrote a Java program which generates HMAC SHA hash code, But due to some reason I have to write the same code in NodeJs/JavaScript. I tried googling around but did not get anything. In this Java code, I am passing URI and Key as arguments, to generate the hash code, where URI contains Timestamp.
The java code is as :
public static String calcMAC(String data, byte[] key) throws Exception {
String result=null;
SecretKeySpec signKey = new SecretKeySpec(key, SecurityConstants.HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(SecurityConstants.HMAC_SHA1_ALGORITHM);
mac.init(signKey);
byte[] rawHmac;
try {
rawHmac = mac.doFinal(data.getBytes("US-ASCII"));
result = Base64.encodeBase64String(rawHmac);
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
public static void main(String args[]) {
String timestamp = args[0];
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC("/req?app_id=47ca34" + timestamp + "=2018-05-22T12:02:15Z",
key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to achieve the same goal in NodeJs/JavaScript?
Note:: I have to call this script from Postman pre-request script.
The crypto module should do this for you, you can substitute the 'data' variable with whatever you want to hash:
const crypto = require('crypto');
const data = 'The fault dear Brutus lies not in our stars';
const key = Buffer.from('d134hjeefcgkahvg32ajkdbaff84ff180', 'utf8');
const hash = crypto.createHmac('sha1', key).update(data).digest('base64');
const uriEncodedHash = encodeURIComponent(hash);
console.log('Hash: ' + uriEncodedHash);
Hashing the data in both Java and Node.js gives me the result (URI Encoded) of:
TJJ3xj93m8bfVpGoucluMQqkB0o%3D
The same Java code would be:
public static void main(String args[]) {
String data = "The fault dear Brutus lies not in our stars";
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC(data, key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Again, we can put anything into 'data' we want.

Tableau Integration with Web project

I am doing Tableau integration with web project using java script api. I have configured my ip in tableau server using commnad :tabadmin set wgserver.trusted_hosts "" and respective commands .But I am not able to get the ticket, ended up with -1. I have followed all configuration steps.
public class TableauServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public TableauServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String user = "raghu";
final String wgserver = "103.xxx.xxx.xx";
final String dst = "views/Regional/College?:iid=1";
final String params = ":embed=yes&:toolbar=yes";
String ticket = getTrustedTicket(wgserver, user, request.getRemoteAddr());
if ( !ticket.equals("-1") ) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "http://" + wgserver + "/trusted/" + ticket + "/" + dst + "?" + params);
}
else
// handle error
throw new ServletException("Invalid ticket " + ticket);
}
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
private String getTrustedTicket(String wgserver, String user, String remoteAddr)
throws ServletException
{
OutputStreamWriter out = null;
BufferedReader in = null;
try {
// Encode the parameters
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(user, "UTF-8"));
data.append("&");
data.append(URLEncoder.encode("client_ip", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(remoteAddr, "UTF-8"));
// Send the request
URL url = new URL("http://" + wgserver + "/trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ( (line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception e) {
throw new ServletException(e);
}
finally {
try {
if (in != null) in.close();
if (out != null) out.close();
}
catch (IOException e) {}
}
}
}
I think you are missing 'target_site' parameter in your URL where you get trusted ticket, its needed if you don't have the 'views/Regional/College' in your default site.
I had gone through a lot of frustration with the '-1' ticket too!
One thing you might try is restarting the tableau server after you have added your web server IP to the trusted_hosts of tableau.
Another thing we ended up doing was adding both the internal ip and external ip of the web server to trusted_hosts on tableau. Since you are using 103.xxx.xxx.xx as your tableau server I am assuming both servers live on the same internal network. You might try that if everything else fails.
My code is almost exactly same as yours and works fine. So if your problem persists, it must be something related to configuration.
here is my code:
private String getAuthenticationTicket(String tableauServerUserName,String tableauServerUrl, String targetSite) {
OutputStreamWriter out = null;
BufferedReader in = null;
try {
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(tableauServerUserName, Constant.UTF_8));
data.append("&");
data.append(URLEncoder.encode("target_site", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(targetSite, Constant.UTF_8));
URL url = new URL(tableauServerUrl + "/" + "trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception ex) {
//log stuff, handle error
return null;
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException ex) {
//log stuff, handle error
}
}
}

Categories

Resources