Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass byte arrays between Java and JavaScript

I need to access SecureRandom Java Object from Javascript. My ultimate goal is to grab 4 bytes from PRNG and convert it to Javascript integer variable. According to http://download.oracle.com/javase/1.4.2/docs/api/java/security/SecureRandom.html, the following two lines of Java code are supposed to do grab 4 random bytes:

byte bytes[] = new byte[4];
random.nextBytes(bytes);

My problems is that I don't know how to 1) allocate byte array suitable for passing to Java method 2) parse that array into integer afterwards

So far I have managed to getSeed() method which returns an array of random bytes. When I render HTML code provided below in Firefox it shows "[B@16f70a4", which appears to be a pointer or something.

<script>
var sprng = new java.security.SecureRandom();
random = sprng.getSeed(4);
document.write(random + "<br/>\n");
</script>

This makes me think that I succeed to instantiate and access Java class, but have a problem with type conversion.

Can anyone please help me to write allocateJavaByteArray(N) and convertJavaByteArrayToInt(N) to let the following code work:

var sprng = new java.security.SecureRandom();
var nextBytes = allocateJavaByteArray(4);
srng.nextBytes(nextBytes);
var nextInt = convertJavaByteArrayToInt(4);

Thank you in advance.

like image 622
abb Avatar asked Oct 01 '10 12:10

abb


1 Answers

You could implement convertJavaByteArrayToInt like this:

function convertJavaByteArrayToInt(bytes) {
  var r = 0;
  for (var i = 0; i < bytes.length; i++) {
    r += (bytes[i] & 0xff) << (8 * i);
  }
  return r;
}

allocateJavaByteArray is difficult to implement, because we cannot get the Class of byte. So it's not possible to use java.lang.reflect.Array.newInstance to create a byte[] instance. But here is a tricky implementation:

function allocateJavaByteArray(n) {
  var r = "";
  for (var i = 0; i < n; i++) {
    r += "0";
  }
  return new java.lang.String(r).getBytes();
}

updated: It seems that above code not worked in FireFox 3.6. Here is another allocateJavaByteArray implementation, have a try:

function allocateJavaByteArray(n) {
  var r = new java.io.ByteArrayOutputStream(4);
  for (var i = 0; i < n; i++) {
    r.write(0);
  }
  return r.toByteArray();
}
like image 120
baotuo Avatar answered Sep 22 '22 08:09

baotuo