I have 16 bytes array data and need to convert that into similar output as OpenSSL BN_bin2bn
provides. Per OpenSSL documents:
BN_bin2bn() converts the positive integer in big-endian form of length len at s into a BIGNUM and places it in ret. If ret is NULL, a new BIGNUM is created.
I am having hard time to do so. BN_bin2bn
uses unsigned long to represent the value but in Java unsigned doesn't support. I tried below mentioned code to implement the same but in this only first 4 bytes of data matches with the bin2bn. Rest of data is different. Only possible reason is that in C unsigned long can store 16 bytes of data but in Java only 8 bytes can be stored.
For 5-8 bytes when i am trying to convert to unsigned then it crosses the 8 byte limit and giving negative value for the long variable.
I also tried to use BigInteger
. Result is same. First 4 bytes are matching but after result doesn't match. Any help is much appreciated.. Here is the code:
byte[] arrayValue = hexToByteArray("53ABA93B9131C439D2942C7CBC483FA5");
long op1 = 0L;
int n = 16 , m = 7;
int x = 0;
while (n-- > 0) {
op1 = (op1 << 8L) | (0xFF & arrayValue[x++]);
System.out.println(op1);
if (m-- == 0) {
op1 = 0L;
}
}
The output is:
83
21419
5483433
1403758907
359362280337
91996743766321
23551166404178372
6029098599469663289
210
53908
13800492
3532926076
904429075644
231533843364936
59272663901423679
-3272942114945089627
With Big Integer:
BigInteger op = BigInteger.ZERO;
while (n-- > 0) {
int temp1 = 0xFF & arrayValue[k++];
op = op.shiftLeft(8).or(new BigInteger(String.valueOf(temp1)));
System.out.println(op);
}
The output is:
83
21419
5483433
1403758907
359362280337
91996743766321
23551166404178372
6029098599469663289
210
53908
13800492
3532926076
904429075644
231533843364936
Output of bin2bn method:
83
21419
5483433
1403758907
2879994769
2839253297
999371204
2435957817
210
53908
13800492
3532926076
2485943484
746372168
2092714047
3158851493