2
\$\begingroup\$

Please refrain from negative comments about the code being poor and inefficient and not idiomatic. I know that much, and that's why I'm here.

I need a function, that takes a byte array and length and returns a byte array. The function need to do the following:

  • Drop any leading zeroes in the byte array
  • If the array length is shorter than passed length parameter, pad the array with leading zeroes up to the passed length

I'm not worried to much about efficiency (e.g. removing a zero only for adding it back later), although I don't mind improvements here, but what I'm really after is to make the code more javascript idiomatic. Can I use Array.map or Array.filter here, for example?

function normalize(byteArray, length) {
  var padding = 0;
  while(padding < byteArray.length && byteArray[padding] == 0) {
    padding++;
  }
  byteArray = byteArray.slice(padding);
  while(byteArray.length < length) {
    byteArray = [0].concat(byteArray);
  }
  return byteArray;
}

Context: the byte array passed to this function comes for a BigInteger value. BigInteger has toByteArray method that produces the array, that needs to be fixed up by the function in question. toByteArray method usually does not produce arrays longer than needed for underlying integer, but sometimes it adds an extra zero byte in front. From the integer perspecive it's all the same, but where the resulting array is going to be consumed (in the printing/formatting function) a certain length is expected, so that the data can be laid out properly. Thus, this function.

\$\endgroup\$
  • \$\begingroup\$ What RSA library are you using that does that? \$\endgroup\$ – 200_success Nov 23 '16 at 0:03
  • \$\begingroup\$ @200_success: it's jsrsasign. The keys components are returned as BigInteger's and then when you call .toByteArray on them you can observe the type of behaviour I described. Maybe I'm not using it properly. But I'd still like improvements on the function posted. \$\endgroup\$ – Andrew Savinykh Nov 23 '16 at 0:04
  • \$\begingroup\$ Are you looking at KEYUTIL? If it's returning integers, then you're probably using it wrong, and trying to solve the wrong problem by padding it. But I can't say, based on this limited snippet of code that you posted, what the right solution is. \$\endgroup\$ – 200_success Nov 23 '16 at 0:10
  • \$\begingroup\$ I suggest that you post your entire encryption or signing code, if you want a useful review. \$\endgroup\$ – 200_success Nov 23 '16 at 0:11
  • 1
    \$\begingroup\$ If you want to transmit an RSA key, use the PEM format like everyone else does. Inventing your own non-standard format is just asking for trouble. \$\endgroup\$ – 200_success Nov 23 '16 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.