summaryrefslogtreecommitdiff
path: root/src/bn.c
blob: b5333c9cbc2ebba7052c2a288cb615772d5696f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
/**
 * XML Security Library (http://www.aleksey.com/xmlsec).
 *
 * Big Numbers.
 *
 * This is free software; see Copyright file in the source
 * distribution for preciese wording.
 *
 * Copyright (C) 2002-2016 Aleksey Sanin <aleksey@aleksey.com>. All Rights Reserved.
 * Copyright (C) 2003 Cordys R&D BV, All rights reserved.
 */
#include "globals.h"

#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include <libxml/tree.h>

#include <xmlsec/xmlsec.h>
#include <xmlsec/xmltree.h>
#include <xmlsec/base64.h>
#include <xmlsec/bn.h>
#include <xmlsec/errors.h>

/* table for converting hex digits back to bytes */
static const int xmlSecBnLookupTable[] =
{
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};

static const char xmlSecBnRevLookupTable[] =
{
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};

/*****************************************************************************
 *
 * xmlSecBn
 *
 ****************************************************************************/
/**
 * xmlSecBnCreate:
 * @size:       the initial allocated BN size.
 *
 * Creates a new BN object. Caller is responsible for destroying it
 * by calling @xmlSecBnDestroy function.
 *
 * Returns: the newly BN or a NULL if an error occurs.
 */
xmlSecBnPtr
xmlSecBnCreate(xmlSecSize size) {
    return(xmlSecBufferCreate(size));
}

/**
 * xmlSecBnDestroy:
 * @bn:         the pointer to BN.
 *
 * Destroys @bn object created with @xmlSecBnCreate function.
 */
void
xmlSecBnDestroy(xmlSecBnPtr bn) {
    xmlSecBufferDestroy(bn);
}

/**
 * xmlSecBnInitialize:
 * @bn:         the pointer to BN.
 * @size:       the initial allocated BN size.
 *
 * Initializes a BN object. Caller is responsible for destroying it
 * by calling @xmlSecBnFinalize function.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnInitialize(xmlSecBnPtr bn, xmlSecSize size) {
    return(xmlSecBufferInitialize(bn, size));
}

/**
 * xmlSecBnFinalize:
 * @bn:         the pointer to BN.
 *
 * Destroys @bn object created with @xmlSecBnInitialize function.
 */
void
xmlSecBnFinalize(xmlSecBnPtr bn) {
    xmlSecBufferFinalize(bn);
}

/**
 * xmlSecBnGetData:
 * @bn:         the pointer to BN.
 *
 * Gets pointer to the binary @bn representation.
 *
 * Returns: pointer to binary BN data or NULL if an error occurs.
 */
xmlSecByte*
xmlSecBnGetData(xmlSecBnPtr bn) {
    return(xmlSecBufferGetData(bn));
}

/**
 * xmlSecBnSetData:
 * @bn:         the pointer to BN.
 * @data:       the pointer to new BN binary data.
 * @size:       the size of new BN data.
 *
 * Sets the value of @bn to @data.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnSetData(xmlSecBnPtr bn, const xmlSecByte* data, xmlSecSize size) {
    return(xmlSecBufferSetData(bn, data, size));
}

/**
 * xmlSecBnGetSize:
 * @bn:         the pointer to BN.
 *
 * Gets the size of binary data in @bn.
 *
 * Returns: the size of binary data.
 */
xmlSecSize
xmlSecBnGetSize(xmlSecBnPtr bn) {
    return(xmlSecBufferGetSize(bn));
}

/**
 * xmlSecBnZero:
 * @bn:         the pointer to BN.
 *
 * Sets the value of @bn to zero.
 */
void
xmlSecBnZero(xmlSecBnPtr bn) {
    xmlSecBufferEmpty(bn);
}

/**
 * xmlSecBnFromString:
 * @bn:         the pointer to BN.
 * @str:        the string with BN.
 * @base:       the base for @str.
 *
 * Reads @bn from string @str assuming it has base @base.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnFromString(xmlSecBnPtr bn, const xmlChar* str, xmlSecSize base) {
    xmlSecSize i, len, size;
    xmlSecByte ch;
    xmlSecByte* data;
    int positive;
    int nn;
    int ret;

    xmlSecAssert2(bn != NULL, -1);
    xmlSecAssert2(str != NULL, -1);
    xmlSecAssert2(base > 1, -1);
    xmlSecAssert2(base <= sizeof(xmlSecBnRevLookupTable), -1);

    /* trivial case */
    len = xmlStrlen(str);
    if(len == 0) {
        return(0);
    }

    /* The result size could not exceed the input string length
     * because each char fits inside a byte in all cases :)
     * In truth, it would be likely less than 1/2 input string length
     * because each byte is represented by 2 chars. If needed,
     * buffer size would be increased by Mul/Add functions.
     * Finally, we can add one byte for 00 or 10 prefix.
     */
    ret = xmlSecBufferSetMaxSize(bn, xmlSecBufferGetSize(bn) + len / 2 + 1 + 1);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnRevLookupTable",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "size=%d", len / 2 + 1);
        return (-1);
    }

    /* figure out if it is positive or negative number */
    positive = 1;
    i = 0;
    while(i < len) {
        ch = str[i++];

        /* skip spaces */
        if(isspace(ch)) {
                continue;
        }

        /* check if it is + or - */
        if(ch == '+') {
            positive = 1;
            break;
        } else if(ch == '-') {
            positive = 0;
            break;
        }

        /* otherwise, it must be start of the number */
        nn = xmlSecBnLookupTable[ch];
        if((nn >= 0) && ((xmlSecSize)nn < base)) {
            xmlSecAssert2(i > 0, -1);

            /* no sign, positive by default */
            positive = 1;
            --i; /* make sure that we will look at this character in next loop */
            break;
        } else {
                xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        NULL,
                        XMLSEC_ERRORS_R_INVALID_DATA,
                        "char=%c;base=%d",
                        ch, base);
                return (-1);
        }
    }

    /* now parse the number itself */
    while(i < len) {
        ch = str[i++];
        if(isspace(ch)) {
                continue;
        }

        xmlSecAssert2(ch <= sizeof(xmlSecBnLookupTable), -1);
        nn = xmlSecBnLookupTable[ch];
        if((nn < 0) || ((xmlSecSize)nn > base)) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        NULL,
                        XMLSEC_ERRORS_R_INVALID_DATA,
                        "char=%c;base=%d",
                        ch, base);
                return (-1);
        }

        ret = xmlSecBnMul(bn, base);
        if(ret < 0) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnMul",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "base=%d", base);
                return (-1);
        }

        ret = xmlSecBnAdd(bn, nn);
        if(ret < 0) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnAdd",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "base=%d", base);
                return (-1);
}
    }

    /* check if we need to add 00 prefix, do this for empty bn too */
    data = xmlSecBufferGetData(bn);
    size = xmlSecBufferGetSize(bn);
    if(((size > 0) && (data[0] > 127)) || (size == 0))  {
        ch = 0;
        ret = xmlSecBufferPrepend(bn, &ch, 1);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                NULL,
                "xmlSecBufferPrepend",
                XMLSEC_ERRORS_R_XMLSEC_FAILED,
                "base=%d", base);
            return (-1);
        }
    }

    /* do 2's compliment and add 1 to represent negative value */
    if(positive == 0) {
        data = xmlSecBufferGetData(bn);
        size = xmlSecBufferGetSize(bn);
        for(i = 0; i < size; ++i) {
            data[i] ^= 0xFF;
        }

        ret = xmlSecBnAdd(bn, 1);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                NULL,
                "xmlSecBnAdd",
                XMLSEC_ERRORS_R_XMLSEC_FAILED,
                "base=%d", base);
            return (-1);
        }
    }

    return(0);
}

/**
 * xmlSecBnToString:
 * @bn:         the pointer to BN.
 * @base:       the base for returned string.
 *
 * Writes @bn to string with base @base. Caller is responsible for
 * freeing returned string with @xmlFree.
 *
 * Returns: the string represenataion if BN or a NULL if an error occurs.
 */
xmlChar*
xmlSecBnToString(xmlSecBnPtr bn, xmlSecSize base) {
    xmlSecBn bn2;
    int positive = 1;
    xmlChar* res;
    xmlSecSize i, len, size;
    xmlSecByte* data;
    int ret;
    int nn;
    xmlChar ch;

    xmlSecAssert2(bn != NULL, NULL);
    xmlSecAssert2(base > 1, NULL);
    xmlSecAssert2(base <= sizeof(xmlSecBnRevLookupTable), NULL);


    /* copy bn */
    data = xmlSecBufferGetData(bn);
    size = xmlSecBufferGetSize(bn);
    ret = xmlSecBnInitialize(&bn2, size);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
            NULL,
            "xmlSecBnCreate",
            XMLSEC_ERRORS_R_XMLSEC_FAILED,
            "size=%d", size);
        return (NULL);
    }

    ret = xmlSecBnSetData(&bn2, data, size);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
            NULL,
            "xmlSecBnSetData",
            XMLSEC_ERRORS_R_XMLSEC_FAILED,
            "size=%d", size);
        xmlSecBnFinalize(&bn2);
        return (NULL);
    }

    /* check if it is a negative number or not */
    data = xmlSecBufferGetData(&bn2);
    size = xmlSecBufferGetSize(&bn2);
    if((size > 0) && (data[0] > 127)) {
        /* subtract 1 and do 2's compliment */
        ret = xmlSecBnAdd(&bn2, -1);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnAdd",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "size=%d", size);
            xmlSecBnFinalize(&bn2);
            return (NULL);
        }
        for(i = 0; i < size; ++i) {
            data[i] ^= 0xFF;
        }

        positive = 0;
    } else {
        positive = 1;
    }

    /* Result string len is
     *      len = log base (256) * <bn size>
     * Since the smallest base == 2 then we can get away with
     *      len = 8 * <bn size>
     */
    len = 8 * size + 1 + 1;
    res = (xmlChar*)xmlMalloc(len + 1);
    if(res == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            NULL,
                            XMLSEC_ERRORS_R_MALLOC_FAILED,
                            "len=%d", len);
        xmlSecBnFinalize(&bn2);
        return (NULL);
    }
    memset(res, 0, len + 1);

    for(i = 0; (xmlSecBufferGetSize(&bn2) > 0) && (i < len); i++) {
        if(xmlSecBnDiv(&bn2, base, &nn) < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnDiv",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "base=%d", base);
            xmlFree(res);
            xmlSecBnFinalize(&bn2);
            return (NULL);
        }
        xmlSecAssert2((size_t)nn < sizeof(xmlSecBnRevLookupTable), NULL);
        res[i] = xmlSecBnRevLookupTable[nn];
    }
    xmlSecAssert2(i < len, NULL);

    /* we might have '0' at the beggining, remove it but keep one zero */
    for(len = i; (len > 1) && (res[len - 1] == '0'); len--);
    res[len] = '\0';

    /* add "-" for negative numbers */
    if(positive == 0) {
        res[len] = '-';
        res[++len] = '\0';
    }

    /* swap the string because we wrote it in reverse order */
    for(i = 0; i < len / 2; i++) {
        ch = res[i];
        res[i] = res[len - i - 1];
        res[len - i - 1] = ch;
    }

    xmlSecBnFinalize(&bn2);
    return(res);
}

/**
 * xmlSecBnFromHexString:
 * @bn:         the pointer to BN.
 * @str:        the string with BN.
 *
 * Reads @bn from hex string @str.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnFromHexString(xmlSecBnPtr bn, const xmlChar* str) {
    return(xmlSecBnFromString(bn, str, 16));
}

/**
 * xmlSecBnToHexString:
 * @bn:         the pointer to BN.
 *
 * Writes @bn to hex string. Caller is responsible for
 * freeing returned string with @xmlFree.
 *
 * Returns: the string represenataion if BN or a NULL if an error occurs.
 */
xmlChar*
xmlSecBnToHexString(xmlSecBnPtr bn) {
    return(xmlSecBnToString(bn, 16));
}

/**
 * xmlSecBnFromDecString:
 * @bn:         the pointer to BN.
 * @str:        the string with BN.
 *
 * Reads @bn from decimal string @str.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnFromDecString(xmlSecBnPtr bn, const xmlChar* str) {
    return(xmlSecBnFromString(bn, str, 10));
}

/**
 * xmlSecBnToDecString:
 * @bn:         the pointer to BN.
 *
 * Writes @bn to decimal string. Caller is responsible for
 * freeing returned string with @xmlFree.
 *
 * Returns: the string represenataion if BN or a NULL if an error occurs.
 */
xmlChar*
xmlSecBnToDecString(xmlSecBnPtr bn) {
    return(xmlSecBnToString(bn, 10));
}

/**
 * xmlSecBnMul:
 * @bn:                 the pointer to BN.
 * @multiplier:         the multiplier.
 *
 * Multiplies @bn with @multiplier.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnMul(xmlSecBnPtr bn, int multiplier) {
    xmlSecByte* data;
    int over;
    xmlSecSize i;
    xmlSecByte ch;
    int ret;

    xmlSecAssert2(bn != NULL, -1);
    xmlSecAssert2(multiplier > 0, -1);

    if(multiplier == 1) {
        return(0);
    }

    data = xmlSecBufferGetData(bn);
    i = xmlSecBufferGetSize(bn);
    over = 0;
    while(i > 0) {
        xmlSecAssert2(data != NULL, -1);

        over    = over + multiplier * data[--i];
        data[i] = over % 256;
        over    = over / 256;
    }

    while(over > 0) {
        ch      = over % 256;
        over    = over / 256;

        ret = xmlSecBufferPrepend(bn, &ch, 1);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBufferPrepend",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "size=1");
            return (-1);
        }
    }

    return(0);
}

/**
 * xmlSecBnDiv:
 * @bn:         the pointer to BN.
 * @divider:    the divider
 * @mod:        the pointer for modulus result.
 *
 * Divides @bn by @divider and places modulus into @mod.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnDiv(xmlSecBnPtr bn, int divider, int* mod) {
    int over;
    xmlSecSize i, size;
    xmlSecByte* data;
    int ret;

    xmlSecAssert2(bn != NULL, -1);
    xmlSecAssert2(divider > 0, -1);
    xmlSecAssert2(mod != NULL, -1);

    if(divider == 1) {
        return(0);
    }

    data = xmlSecBufferGetData(bn);
    size = xmlSecBufferGetSize(bn);
    for(over = 0, i = 0; i < size; i++) {
        xmlSecAssert2(data != NULL, -1);

        over    = over * 256 + data[i];
        data[i] = over / divider;
        over    = over % divider;
    }
    (*mod) = over;

    /* remove leading zeros */
    for(i = 0; i < size; i++) {
        xmlSecAssert2(data != NULL, -1);

        if(data[i] != 0) {
            break;
        }
    }
    if(i > 0) {
        ret = xmlSecBufferRemoveHead(bn, i);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBufferRemoveHead",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "size=%d", i);
            return (-1);
        }
    }
    return(0);
}

/**
 * xmlSecBnAdd:
 * @bn:         the pointer to BN.
 * @delta:      the delta.
 *
 * Adds @delta to @bn.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnAdd(xmlSecBnPtr bn, int delta) {
    int over, tmp;
    xmlSecByte* data;
    xmlSecSize i;
    xmlSecByte ch;
    int ret;

    xmlSecAssert2(bn != NULL, -1);

    if(delta == 0) {
        return(0);
    }

    data = xmlSecBufferGetData(bn);
    if(delta > 0) {
        for(over = delta, i = xmlSecBufferGetSize(bn); (i > 0) && (over > 0) ;) {
                xmlSecAssert2(data != NULL, -1);

            tmp     = data[--i];
                over   += tmp;
                data[i] = over % 256;
                over    = over / 256;
        }

        while(over > 0) {
                ch      = over % 256;
                over    = over / 256;

                ret = xmlSecBufferPrepend(bn, &ch, 1);
                if(ret < 0) {
                    xmlSecError(XMLSEC_ERRORS_HERE,
                                NULL,
                                "xmlSecBufferPrepend",
                                XMLSEC_ERRORS_R_XMLSEC_FAILED,
                                "size=1");
                    return (-1);
                }
        }
    } else {
        for(over = -delta, i = xmlSecBufferGetSize(bn); (i > 0) && (over > 0);) {
                xmlSecAssert2(data != NULL, -1);

            tmp     = data[--i];
            if(tmp < over) {
                data[i] = 0;
                over = (over - tmp) / 256;
            } else {
                data[i] = tmp - over;
                over = 0;
            }
        }
    }
    return(0);
}

/**
 * xmlSecBnReverse:
 * @bn:         the pointer to BN.
 *
 * Reverses bytes order in @bn.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecBnReverse(xmlSecBnPtr bn) {
    xmlSecByte* data;
    xmlSecSize i, j, size;
    xmlSecByte ch;

    xmlSecAssert2(bn != NULL, -1);

    data = xmlSecBufferGetData(bn);
    size = xmlSecBufferGetSize(bn);
    for(i = 0, j = size - 1; i < size / 2; ++i, --j) {
        xmlSecAssert2(data != NULL, -1);

        ch       = data[i];
        data[i]  = data[j];
        data[j]  = ch;
    }

    return(0);
}

/**
 * xmlSecBnCompare:
 * @bn:         the pointer to BN.
 * @data:       the data to compare BN to.
 * @dataSize:   the @data size.
 *
 * Compares the @bn with @data.
 *
 * Returns: 0 if data is equal, negative value if @bn is less or positive value if @bn
 * is greater than @data.
 */
int
xmlSecBnCompare(xmlSecBnPtr bn, const xmlSecByte* data, xmlSecSize dataSize) {
    xmlSecByte* bnData;
    xmlSecSize bnSize;

    xmlSecAssert2(bn != NULL, -1);

    bnData = xmlSecBnGetData(bn);
    bnSize = xmlSecBnGetSize(bn);

    /* skip zeros in the beggining */
    while((dataSize > 0) && (data != 0) && (data[0] == 0)) {
        ++data;
        --dataSize;
    }
    while((bnSize > 0) && (bnData != 0) && (bnData[0] == 0)) {
        ++bnData;
        --bnSize;
    }

    if(((bnData == NULL) || (bnSize == 0)) && ((data == NULL) || (dataSize == 0))) {
        return(0);
    } else if((bnData == NULL) || (bnSize == 0)) {
        return(-1);
    } else if((data == NULL) || (dataSize == 0)) {
        return(1);
    } else if(bnSize < dataSize) {
        return(-1);
    } else if(bnSize > dataSize) {
        return(-1);
    }

    xmlSecAssert2(bnData != NULL, -1);
    xmlSecAssert2(data != NULL, -1);
    xmlSecAssert2(bnSize == dataSize, -1);

    return(memcmp(bnData, data, dataSize));
}

/**
 * xmlSecBnCompareReverse:
 * @bn:         the pointer to BN.
 * @data:       the data to compare BN to.
 * @dataSize:   the @data size.
 *
 * Compares the @bn with reverse @data.
 *
 * Returns: 0 if data is equal, negative value if @bn is less or positive value if @bn
 * is greater than @data.
 */
int
xmlSecBnCompareReverse(xmlSecBnPtr bn, const xmlSecByte* data, xmlSecSize dataSize) {
    xmlSecByte* bnData;
    xmlSecSize bnSize;
    xmlSecSize i, j;

    xmlSecAssert2(bn != NULL, -1);

    bnData = xmlSecBnGetData(bn);
    bnSize = xmlSecBnGetSize(bn);

    /* skip zeros in the beggining */
    while((dataSize > 0) && (data != 0) && (data[dataSize - 1] == 0)) {
        --dataSize;
    }
    while((bnSize > 0) && (bnData != 0) && (bnData[0] == 0)) {
        ++bnData;
        --bnSize;
    }

    if(((bnData == NULL) || (bnSize == 0)) && ((data == NULL) || (dataSize == 0))) {
        return(0);
    } else if((bnData == NULL) || (bnSize == 0)) {
        return(-1);
    } else if((data == NULL) || (dataSize == 0)) {
        return(1);
    } else if(bnSize < dataSize) {
        return(-1);
    } else if(bnSize > dataSize) {
        return(-1);
    }

    xmlSecAssert2(bnData != NULL, -1);
    xmlSecAssert2(data != NULL, -1);
    xmlSecAssert2(bnSize == dataSize, -1);
    for(i = 0, j = dataSize - 1; i < dataSize; ++i, --j) {
        if(bnData[i] < data[j]) {
            return(-1);
        } else if(data[j] < bnData[i]) {
            return(1);
        }
    }

    return(0);
}

/**
 * xmlSecBnGetNodeValue:
 * @bn:         the pointer to BN.
 * @cur:        the poitner to an XML node.
 * @format:     the BN format.
 * @reverse:    if set then reverse read buffer after reading.
 *
 * Converts the node content from @format to @bn.
 *
 * Returns: 0 on success and a negative values if an error occurs.
 */
int
xmlSecBnGetNodeValue(xmlSecBnPtr bn, xmlNodePtr cur, xmlSecBnFormat format, int reverse) {
    xmlChar* content;
    int ret;

    xmlSecAssert2(bn != NULL, -1);
    xmlSecAssert2(cur != NULL, -1);

    switch(format) {
    case xmlSecBnBase64:
        ret = xmlSecBufferBase64NodeContentRead(bn, cur);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBufferBase64NodeContentRead",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
        break;
    case xmlSecBnHex:
        content = xmlNodeGetContent(cur);
        if(content == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlNodeGetContent",
                        XMLSEC_ERRORS_R_XML_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
        ret = xmlSecBnFromHexString(bn, content);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnFromHexString",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            xmlFree(content);
            return(-1);
        }
        xmlFree(content);
        break;
    case xmlSecBnDec:
        content = xmlNodeGetContent(cur);
        if(content == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlNodeGetContent",
                        XMLSEC_ERRORS_R_XML_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
        ret = xmlSecBnFromDecString(bn, content);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnFromDecString",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            xmlFree(content);
            return(-1);
        }
        xmlFree(content);
        break;
    }

    if(reverse != 0) {
        ret = xmlSecBnReverse(bn);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnReverse",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
    }
    return(0);
}

/**
 * xmlSecBnSetNodeValue:
 * @bn:                 the pointer to BN.
 * @cur:                the poitner to an XML node.
 * @format:             the BN format.
 * @reverse:            the flag that indicates whether to reverse the buffer before writing.
 * @addLineBreaks:      the flag; it is equal to 1 then linebreaks will be added before and after new buffer content.
 *
 * Converts the @bn and sets it to node content.
 *
 * Returns: 0 on success and a negative values if an error occurs.
 */
int
xmlSecBnSetNodeValue(xmlSecBnPtr bn, xmlNodePtr cur, xmlSecBnFormat format, int reverse, int addLineBreaks) {
    xmlChar* content;
    int ret;

    xmlSecAssert2(bn != NULL, -1);
    xmlSecAssert2(cur != NULL, -1);

    if(reverse != 0) {
        ret = xmlSecBnReverse(bn);
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnReverse",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
    }

    if(addLineBreaks) {
        xmlNodeAddContent(cur, xmlSecStringCR);
    }

    switch(format) {
    case xmlSecBnBase64:
        ret = xmlSecBufferBase64NodeContentWrite(bn, cur, xmlSecBase64GetDefaultLineSize());
        if(ret < 0) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBufferBase64NodeContentWrite",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            return(-1);
        }
        break;
    case xmlSecBnHex:
        content = xmlSecBnToHexString(bn);
        if(content == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnToHexString",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            xmlFree(content);
            return(-1);
        }
        xmlNodeSetContent(cur, content);
        xmlFree(content);
        break;
    case xmlSecBnDec:
        content = xmlSecBnToDecString(bn);
        if(content == NULL) {
            xmlSecError(XMLSEC_ERRORS_HERE,
                        NULL,
                        "xmlSecBnToDecString",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        XMLSEC_ERRORS_NO_MESSAGE);
            xmlFree(content);
            return(-1);
        }
        xmlNodeSetContent(cur, content);
        xmlFree(content);
        break;
    }

    if(addLineBreaks) {
        xmlNodeAddContent(cur, xmlSecStringCR);
    }

    return(0);
}

/**
 * xmlSecBnBlobSetNodeValue:
 * @data:       the pointer to BN blob.
 * @dataSize:   the size of BN blob.
 * @cur:        the poitner to an XML node.
 * @format:     the BN format.
 * @reverse:    the flag that indicates whether to reverse the buffer before writing.
 * @addLineBreaks:  if the flag is equal to 1 then
 *              linebreaks will be added before and after
 *              new buffer content.
 *
 * Converts the @blob and sets it to node content.
 *
 * Returns: 0 on success and a negative values if an error occurs.
 */
int
xmlSecBnBlobSetNodeValue(const xmlSecByte* data, xmlSecSize dataSize,
                         xmlNodePtr cur, xmlSecBnFormat format, int reverse,
                         int addLineBreaks) {
    xmlSecBn bn;
    int ret;

    xmlSecAssert2(data != NULL, -1);
    xmlSecAssert2(cur != NULL, -1);

    ret = xmlSecBnInitialize(&bn, dataSize);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecBnInitialize",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    ret = xmlSecBnSetData(&bn, data, dataSize);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecBnSetData",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        xmlSecBnFinalize(&bn);
        return(-1);
    }

    ret = xmlSecBnSetNodeValue(&bn, cur, format, reverse, addLineBreaks);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecBnSetNodeValue",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        xmlSecBnFinalize(&bn);
        return(-1);
    }

    xmlSecBnFinalize(&bn);
    return(0);
}