Array with Apache Thrift using server Java & Javascript Client - javascript

im using Javascript to show info generated in Java.
Im talking of 10,000 datas, all of them generated in Java and for porpouse of testing im using random values. Well i want to see this 10,000 values in my javascript page.
I already have a simple Server Java and a Client Javascript to share 2 doubles.
This is the Thrift file for 2 doubles:
namespace java test_thrift
service test{
double number(1:double n1, 2:double n2)
}
This is the code of my Javascript Client
function calc() {
var transport = new Thrift.Transport("/service");
var protocol = new Thrift.Protocol(transport);
var client = new testClient(protocol);
var workbench = Math.random()*1000;
try {
result = client.number(workbench);
$('#result').val(result);
$('#result').css('color', 'black');
document.getElementById("demo").innerHTML = result;
} catch(ouch){
$('#result').val(ouch.why);
$('#result').css('color', 'red');
}
}
Im sending a Random only to get the range of the return. Example: 1 return a value from 3 to 9, 2 return a 9 to 15 value, etc.
And in java i have a testHandler class:
public double number(double n1, double n2) throws TException {
//System.out.println(n1 + " - " + n2);
Random rnd = new Random();
n1 = rnd.nextDouble() * 10 + 1;
n2 = rnd.nextDouble() * 15 + 10;
return n2;
}
Well this returns 1 value. And i want to see all in my Javascript Page. But with 10,000 elements. How can i do this?
Also i want to add that the final struct to share is like this:
dis[10000][3]={
ABC,12.5,13.5,
ACD,14.4,11.5,
.....ETC......}
Im stuck
Found this, but i dont know how to get it work :/
namespace java test_thrift
typedef list<double> Vector
struct test
{
1:i32 rows,
2:i32 cols,
3:list<Vector> data,
}

Use this IDL file
namespace java test_thrift
struct MyPair {
1: double one
2: double two
}
service test{
list<double> number( 1 : list<MyPair> data)
}
The function is then called like so:
var list = [];
for( var i = 0; i < 10000; ++i) {
list.push({
one : Math.random()*1000,
two : Math.random()*1000
});
}
result = client.number(list);
Result should then be your list of returned values, given of course the server end is implemented accordingly.

So, i managed to fix it. Here's a Client JavasCript that make a reequest and a Java server Give back a 10000 x 18 Matrix.
Thrift file:
namespace java test_thrift
struct Cell {
1: string did
2: double l_x
3: double l_y
4: double l_z
5: double m_x
6: double m_y
7: double m_z
8: double a_x
9: double a_y
10: double a_z
11: double g_x
12: double g_y
13: double g_z
14: string d_t
15: double tp
16: double r_q
17: string o_m
18: double b_v
}
service test{
list<Cell> number( 1 : i16 req)
}
Then in Javascript i send only the request:
function calc() {
var transport = new Thrift.Transport("/service");
var protocol = new Thrift.Protocol(transport);
var client = new pruebaClient(protocol);
var workbench = Math.random()*1000;
var div = document.getElementById('deltat');
try {
result = client.number(1);
div.innerHTML = div.innerHTML + '\nReady';
} catch(ouch){
$('#result').val("ERROR");
$('#result').css('color', 'red');
}
}
And in result y have the [10000][18] answer and print it like this:
for (var i = result.length - 1; i >= 0; i--) {
//div.innerHTML = div.innerHTML + '\n' + result[i];
div.insertAdjacentHTML('beforeend', '\n'+result[i].did+' '+result[i].l_x+' '+result[i].l_y+' '+result[i].l_z+' '+result[i].m_x+' '+result[i].m_y+' '+result[i].m_z+' '+result[i].a_x+' '+result[i].a_y+' '+result[i].a_z+' '+result[i].g_x+' '+result[i].g_y+' '+result[i].g_z+' '+result[i].d_t+' '+result[i].tp+' '+result[i].r_q+' '+result[i].o_m+' '+result[i].b_v);
};
}
Finally the handler in my Java Server is like this:
public class TestHandler implements test.Iface {
public Random rnd = new Random();
public static List<Cell> p = new ArrayList<Cell>();
public void test() {
for (int i = 0; i < 10000; i++) {
Cell a = new Cell();
a.did = "SomeString";
a.l_x = rnd.nextDouble()*10+1;
a.l_y = rnd.nextDouble()*10+1;
a.l_z = 0.0;
a.m_x = 0.0;
a.m_y = 0.0;
a.m_z = 0.0;
a.a_x = 0.0;
a.a_y = 0.0;
a.a_z = 0.0;
a.g_x = 0.0;
a.g_y = 0.0;
a.g_z = 0.0;
a.d_t = "String here";
a.tp = 0.0;
a.r_q = 0.0;
a.o_m = "A";
a.b_v = 0.0;
p.add(a);
}
}
#Override
public List<Cell> number(short req) throws TException {
test();
return ips.ReminderBeep.list_d;
}
I hope this will be useful for someone

Related

Convert Java's PBEWithMD5AndDES without salt to JavaScript with crypto

I have the following code for decryption in java, I want that to be implemented in nodejs but the i found many tuto for my problem but they use a salt and that don't work when i try to remove the salt system.
My olds functions from java
public void readLastLogin(File lastLogin) {
try {
final Cipher ciph = this.openCipher(Cipher.DECRYPT_MODE);
final DataInputStream dis = new DataInputStream(new CipherInputStream(new FileInputStream(lastLogin), ciph));
String user = dis.readUTF();
String token = dis.readUTF();
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveLastLogin(File lastLogin, String user, String token) {
try {
final Cipher ciph = this.openCipher(Cipher.ENCRYPT_MODE);
final DataOutputStream dos = new DataOutputStream(new CipherOutputStream(new FileOutputStream(lastLogin), ciph));
dos.writeUTF(user);
dos.writeUTF(token);
dos.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
private Cipher openCipher(final int mode) throws Exception {
final Random rnd = new Random(43287234L);
final byte[] data = new byte[8];
rnd.nextBytes(data);
final PBEParameterSpec spec = new PBEParameterSpec(data, 5);
final SecretKey key = SecretKeyFactory
.getInstance("PBEWithMD5AndDES")
.generateSecret(new PBEKeySpec("mysecretpassword".toCharArray()));
final Cipher ret = Cipher.getInstance("PBEWithMD5AndDES");
ret.init(mode, key, spec);
return ret;
}
I try this but not working
KDF(password, iterations) {
var key = new Buffer(password,'utf-8');
var i;
for (i = 0; i < iterations; i+=1) {
key = crypto.createHash("md5").update(key).digest();
}
return key;
}
getKeyIV(password, iterations) {
var key = this.KDF(password, iterations);
var keybuf = new Buffer(key,'binary').slice(0,8);
var ivbuf = new Buffer(key,'binary').slice(8,16);
return [ keybuf, ivbuf ];
}
decrypt(message) {
var kiv = this.getKeyIV('password' ,5);
var decipher = crypto.createDecipheriv('des-ede', kiv[0], kiv[1]);
var result = decipher.update(message, 'hex', 'utf-8');
return result + decipher.final('utf-8');
}
Edit: The salt generated at runtime of the Java code is hex encoded: 0x0C9D4AE41E8315FC
final byte[] data = new byte[8];
data[0] = 12;
data[1] = -99;
data[2] = 74;
data[3] = -28;
data[4] = 30;
data[5] = -125;
data[6] = 21;
data[7] = -4;
There are three issues in the code:
The Java code uses writeUTF(). This is based on modified UTF-8, with two additional bytes prepended to contain the data size. A NodeJS library for modified UTF-8 is mutf-8.
Instead of des-ede (3DES/2TDEA in ECB mode), des-cbc (DES in CBC mode) must be applied. If DES is not available in the used NodeJS version, it can be mimicked with 3DES/2TDEA in CBC mode, des-ede-cbc, where the 8 bytes key has to be concatenated with itself to a 16 bytes key, reducing 3DES to DES. This workaround has the disadvantage of a performance loss.
The Java code applies a static 8 byte salt because Random() is instantiated with a static seed. This salt can be determined at runtime to (hex encoded): 0x0C9D4AE41E8315FC.
pbewithmd5anddes-js is a port of PBEWithMD5AndDES to NodeJS, from which the KDF(), getKeyIV() and decrypt() methods can be used, but must be adapted taking into account the above points. In addition, the functionality of readUTF() (the counterpart of writeUTF()) must be implemented. One possible solution is:
var crypto = require('crypto');
const { MUtf8Decoder } = require("mutf-8");
var pbewithmd5anddes = {
KDF: function(password,salt,iterations) {
var pwd = Buffer.from(password,'utf-8');
var key = Buffer.concat([pwd, salt]);
var i;
for (i = 0; i < iterations; i+=1) {
key = crypto.createHash('md5').update(key).digest();
}
return key;
},
getKeyIV: function(password,salt,iterations) {
var key = this.KDF(password,salt,iterations);
var keybuf = Buffer.from(key,'binary').subarray(0,8);
var ivbuf = Buffer.from(key,'binary').subarray(8,16);
return [ keybuf, ivbuf ];
},
decrypt: function(payload,password,salt,iterations) {
var encryptedBuffer = Buffer.from(payload,'base64');
var kiv = this.getKeyIV(password,salt,iterations);
//var decipher = crypto.createDecipheriv('des-cbc', kiv[0], kiv[1]); // Fix 1: If supported, apply DES-CBC with key K
var decipher = crypto.createDecipheriv('des-ede-cbc', Buffer.concat([kiv[0], kiv[0]]), kiv[1]); // otherwise DES-EDE-CBC with key K|K
var decryptedBuf = Buffer.concat([decipher.update(encryptedBuffer), decipher.final()])
var decrypted = this.readUTF(decryptedBuf) // Fix 2: apply writeUTF counterpart
return decrypted;
},
readUTF: function(decryptedBuf) {
var decoder = new MUtf8Decoder()
var decryptedData = []
var i = 0;
while (i < decryptedBuf.length){
var lengthObj = decryptedBuf.readInt16BE(i);
var bytesObj = decryptedBuf.subarray(i+2, i+2+lengthObj);
var strObj = decoder.decode(bytesObj)
decryptedData.push(strObj)
i += 2 + lengthObj;
}
return decryptedData;
}
};
Test:
On the Java side, the following is executed:
saveLastLogin(file, "This is the first plaintext with special characters like §, $ and €.", "This is the second plaintext with special characters like §, $ and €.");
The raw ciphertext written to file is Base64 encoded:
Ow8bdeNM0QpNFQaoDe7dhG3k9nWz/UZ6v3+wQVgrD5QvWR/4+sA+YvqtnQBsy35nQkwhwGRBv1h1eOa587NaFtnJUWVHsRsncLWZ05+dD2rYVpcZRA8s6P2iANK6yLr+GO/+UpZpSe0fA4fFqEK1nm3U7NXdyddfuOlZ3h/RiyxK5819LieUne4F8/TpMzT0RIWkxqagbVw=
This can be decrypted on the NodeJS side with:
var payload = 'Ow8bdeNM0QpNFQaoDe7dhG3k9nWz/UZ6v3+wQVgrD5QvWR/4+sA+YvqtnQBsy35nQkwhwGRBv1h1eOa587NaFtnJUWVHsRsncLWZ05+dD2rYVpcZRA8s6P2iANK6yLr+GO/+UpZpSe0fA4fFqEK1nm3U7NXdyddfuOlZ3h/RiyxK5819LieUne4F8/TpMzT0RIWkxqagbVw=';
var password = 'mysecretpassword';
var salt = Buffer.from('0C9D4AE41E8315FC', 'hex');
var iterations = 5;
var decrypted = pbewithmd5anddes.decrypt(payload,password,salt,iterations);
console.log(decrypted);
with the output:
[
'This is the first plaintext with special characters like §, $ and €.',
'This is the second plaintext with special characters like §, $ and €.'
]
Note that the code contains serious vulnerabilities:
PBEWithMD5AndDES uses a key derivation based on the broken MD5 digest (PBKDF1), and as encryption algorithm the deprecated DES (officially withdrawn almost 20 years ago).
Use of a static salt.
An iteration count of 5 is generally much too small.
Random() (unlike SecureRandom()) is not cryptographically strong. Also note that it is not a good idea to use a PRNG like Random() for deterministic key derivation, as the implementation may change, leading to different results even with the same seed.

Generate test case based on two dimensional array

I'm use four arrays to generate difference test case, like below
var phone = ['phone1', 'phone2', 'phone3'];
var browsers = ['chrome', 'firefox'];
var location = ['1324','2434','4234','1234','3243'];
var network = ['3g', '4g', 'wifi'];
var isLogin = ['service worker', 'no service worker'];
How do I write code that will generate the test case (180 difference case). I try for loop and recursion. I just can't seem to figure out a perfect way to do it. note I'm using javascript. can only use array for loop, can't use object due to some reason.
Can anyone give me some inspiration ?
I tried some scenario in Java(Approach can be applicable in same way for Javascript) with recursion, In this case I use 3 arrays and for 2 of them I use recursion.
public class Test3 {
static String[] names = { "Ram", "Shyam", "Mohan", "Rohan", "Saket" };
static String[] citys = { "Bhopal", "Indore", "Ujjan", "Dewas", "Rewa" };
static String[] addresses = { "add1", "add2", "add3", "add4", "add5" };
static StringBuffer buffer = new StringBuffer();
public static void main(String... strings) {
for (String a : names) {
System.out.println(testData(a)+"\n");
buffer.setLength(0);
}
}
public static String testData(String name) {
return generateData(name, 0, -1);
}
public static String generateData(String combination, int countA, int countB) {
if ((countA == names.length - 1) && (countB == names.length - 1)) {
return buffer.toString();
}
if (countB == addresses.length - 1) {
countA = countA + 1;
countB = -1;
}
countB = countB + 1;
buffer.append(combination + citys[countA] + addresses[countB] + "\n");
return generateData(combination, countA, countB);
}
}
Hope this will help!!

Generate CHAP response in java

Currently I'm trying to generate a chap response in java. It works in php... but our backend needs it done in java.
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal)
I've managed to find some javascript code, but the response is off by a few characters.
function getPapPassword(){
//function to add value padding to a string of x length default : null padding
String.prototype.pad = function (length, padding) {
var padding = typeof padding === 'string' && padding.length > 0 ? padding[0] : '\x00'
, length = isNaN(length) ? 0 : ~~length;
return this.length < length ? this + Array(length - this.length + 1).join(padding) : this;
};
//function to convert hex to ascii characters
String.prototype.packHex = function () {
var source = this.length % 2 ? this + '0' : this
, result = '';
for (var i = 0; i < source.length; i = i + 2) {
result += String.fromCharCode(parseInt(source.substr(i, 2), 16));
}
return result;
};
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal);
}
return response;
}
Can anyone point me in the right direction or assist?
Thanks
Okay so what I've done is tried to convert from hex to ascii in java... here is my code.
public class App{
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
public static void main(String[] args) {
App app = new App();
System.out.println("ASCII : " + app.convertHexToString("9f9585f4e88305fde280c762925f37af"));
}
}
The php of the hex challenge output is: Ÿ•…ôèƒýâ€Çb’_7¯
The java output of the hex challenge is: ôèýâÇb_7¯
So I've found that the javascript is exactly the same as the java. Something is happening in php that is changing it. The php version works perfectly when I connect to the UAM with that chap response.

make json string to match exact string for pie chart datasource?how to

here is my recieved JSON string
"{Date:'15/05/2015',y:'6'},
{Date:'01/08/2015',y:'6'},
{Date:'02/08/2015',y:'6'},
{Date:'08/08/2015',y:'72'},
{Date:'09/08/2015',y:'6'},"
i have to make it exactly like that for my datasource in pie chart
var datas = [
{date:"02/02/2015",y:6},
{date:"15/05/2015",y:6},
{date:"01/08/2015",y:6},
{date:"02/08/2015",y:6}
];
here is working js fiddle js fiddle working for json
here is my c sharp code for making json
foreach (KeyValuePair<string, int> pair2 in dic)
{
int perce = pair2.Value;
var perct = ((double)perce / total) * 100;
int perc = Convert.ToInt32(perct);
string datesval = pair2.Key;
StringBuilder sb = new StringBuilder();
sb.Append("Date:'" + datesval + "',y:" + perc + "");
string newq = sb.ToString();
list.Add(newq);
}
StringBuilder sb2 = new StringBuilder();
foreach (string element in list)
{
for (int m = 0; m <= list.Count() - 1; m++)
{
sb2.Append("{" + list[m] + "},");
line = sb2.ToString();
}
break;
}
the string should be modified using javascript
remove (") double quote from start of string and add [ . also remove (,") from end and add ]
also show error Uncaught TypeError: undefined is not a function on line
$('#container').highcharts({
use string builder and eval , I am extentendinng the above from Line you built
string c = line;
StringBuilder builder = new StringBuilder(c);
// builder.Replace(",\"","]");
// builder[0] = '[';
TrimEnd(builder,',');
// builder.AppendFormat("[\"{0}\"]", builder.ToString());
string combine = "["+ builder.ToString();
string newcom = combine + "]";
return newcom;
}
static void TrimEnd(StringBuilder builder, char letter)
{
// ... If last char matches argument, reduce length by 1.
if (builder.Length == 0)
{
string c = "sorry";
}
else if (builder[builder.Length - 1] == letter)
{
builder.Length -= 1;
}
}
in succes of ajax do this
var v = eval(response.d);
now use this in pie chart
2nd error is because jquery files conflict with each other use jquery 1.9.1.js first then graph files

Extract RSA private key from Cryptico.js

I believe this is a pretty basic question, but I'm starting the studies in JavaScript and in RSA, so I'm a little bit lost. I just downloaded the library Cryptico, which gives me an easy to use RSA key gen/encryption/decryption. The public part of the generated RSA Key, can be extracted easily just using the command:
publicKeyString(RsaKey)
Which is:
my.publicKeyString = function(rsakey)
{
pubkey = my.b16to64(rsakey.n.toString(16));
return pubkey;
}
The rsakey.n is defined while generating the key in the function:
function RSAGenerate(B, E)
{
var rng = new SeededRandom();
var qs = B >> 1;
this.e = parseInt(E, 16);
var ee = new BigInteger(E, 16);
for (;;)
{
for (;;)
{
this.p = new BigInteger(B - qs, 1, rng);
if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
}
for (;;)
{
this.q = new BigInteger(qs, 1, rng);
if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
}
if (this.p.compareTo(this.q) <= 0)
{
var t = this.p;
this.p = this.q;
this.q = t;
}
var p1 = this.p.subtract(BigInteger.ONE);
var q1 = this.q.subtract(BigInteger.ONE);
var phi = p1.multiply(q1);
if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0)
{
this.n = this.p.multiply(this.q);
this.d = ee.modInverse(phi);
this.dmp1 = this.d.mod(p1);
this.dmq1 = this.d.mod(q1);
this.coeff = this.q.modInverse(this.p);
break;
}
}
}
But the private part of the key, I just can't understand how to extract, so I'll be able to save public/private key parts and available for later using.
Library Documentation:
https://github.com/wwwtyro/cryptico
RSA is defined in such a way that the values contained in a public key make up a subset of the values contained in the private key. So your private key is already rsakey. Other public key schemes work differently where public and private key values are completely distinct.
Furthermore rsakey.n doesn't fully define the public key. You need at least the public exponent e. It is often simply set to 65537, so this might be hardcoded if you never need to change the key or upgrade the scheme. It's the E in RSAGenerate. It is ignored in this case, because
A (seeded) random RSA key is generated with Tom Wu's RSA key generator with 3 as a hard-coded public exponent.
You can choose a similar encoding of the private key as the public key, but since it has to hold multiple values, I opted for JSON serialization:
(function(c){
var parametersBigint = ["n", "d", "p", "q", "dmp1", "dmq1", "coeff"];
c.privateKeyString = function(rsakey) {
var keyObj = {};
parametersBigint.forEach(function(parameter){
keyObj[parameter] = c.b16to64(rsakey[parameter].toString(16));
});
// e is 3 implicitly
return JSON.stringify(keyObj);
}
c.privateKeyFromString = function(string) {
var keyObj = JSON.parse(string);
var rsa = new RSAKey();
parametersBigint.forEach(function(parameter){
rsa[parameter] = parseBigInt(c.b64to16(keyObj[parameter].split("|")[0]), 16);
});
rsa.e = parseInt("03", 16);
return rsa
}
})(cryptico)

Categories