Large integer algorithm [02] basic operation (Maintenance algorithm)

Source: Internet
Author: User

The previous post briefly introduced the representation of large integers, and this time began to introduce some basic algorithms.

★ Initialize and Clear

The starting point for writing large integer functions is the initialization and elimination of bignum structures, which are used in most of the other algorithms.

For a given bignum structure, there are two cases of initialization: one is to simply point the DP of the BIGNUM structure to NULL, and the other is to allocate a certain amount of dynamic memory when initializing and to point the DP pointer to the memory. In fact, I was going to initialize it in a second way, but considering that the initial memory might be too large to cause memory waste, I decided to use it in two different ways. The advantage of the first approach is that you do not have to consider how much memory to allocate in the back of the programming, memory allocation work to the Bn_grow function to do, reduce the workload, but its shortcomings are more obvious, if the initial memory allocation is too low, in the back may require multiple memory allocation to increase accuracy, efficiency, It's time-consuming to know what's on the heap.

If the DP pointer in the BIGNUM structure has been initialized (null or points to an allocated memory), the other members of the struct must be initialized. The default is 0 after initialization of bignum, so sign = 1, used = 0. If DP is Null,alloc = 0, otherwise alloc = assigned digits (nlimbs).

In order to avoid unlimited allocation of memory, a maximum value of bn_max_limb is set for the decimal place, which is defined in the header file:

#define BN_MAX_LIMB 25600

That is to say, the maximum number of bignum structure can not exceed 25600, in 32-bit environment, each digit length of 32bit, so bignum maximum length is 819200bit, for the encryption algorithm is more than sufficient.

For portability, the following macros are defined (refer to the definition of POLARSSL for better understanding):

#define CiL (sizeof (bn_digit))//chars in limb (byte size per digit)
#define BiL (CiL << 3)//bits in limb (bit size per digit)
#define BILH (CiL << 2)//half bits in limb ( bit size per digit , which is used later by the modulo operation)

#define bn_malloc                      malloc
        #define bn_free                              free    

/** * bignum structure initialization, memory not allocated. */void bn_init (Bignum *x) {    if (x! = NULL)    {        x->sign = 1;        X->alloc = 0;        x->used = 0;        X->DP = NULL;}    } /** * Bignum Structure initializes and allocates memory. * If initialization fails (memory allocation error), return Bn_memory_allocate_fail * If exceeded number limit, return bn_exceed_max_limb */int bn_init_size (bignum *x, size_t nlimbs) {    bn_digit *p;    if (Nlimbs > Bn_max_limb)        return bn_exceed_max_limb;    if (x = NULL)    {        p = (bn_digit *) bn_malloc (nlimbs * ciL);        if (p = = NULL) return bn_memory_allocate_fail;        Memset (P, 0x00, Nlimbs * ciL);    After initialization bignum defaults to 0, so you must set all the values of the memory that P points to 0.        X->sign = 1;        X->alloc = nlimbs;        x->used = 0;        X->DP = P;    }    return 0;}

When you no longer need to use bignum, you should use the Bn_free function to release its allocated memory in a timely manner. The Bn_free function has two functions: one is to clear the bignum's digits and other members, so that if you accidentally use a bignum that has already been cleared, it will not be a problem, and the second is to release the allocated memory.

The DP of the cleared Bignum is set to NULL, so that the function can detect that the bignum has been cleared and avoid multiple memory releases after the function is called again.

void Bn_free (Bignum *x) {    if (x! = null)    {        if (X->DP! = null)        {            memset (X->DP, 0x00, X->alloc * CiL);            Bn_free (X->DP);        }        X->sign = 1;        X->alloc = 0;        x->used = 0;        X->DP = NULL;}    }

★ Increased Accuracy

When storing a value in the bignum, there must be enough digits to hold a full, large integer intact. If the alloc is large enough, you only need to increase the used, otherwise you will need to reallocate memory alloc to meet the requirements.

The Bn_grow function first checks if the required digits (NLIMBS) are greater than alloc, and if not, it does not need to add precision, and the function call ends, thus avoiding memory reallocation and saving time. If the nlimbs is greater than alloc, then it is necessary to reallocate a memory space of Nlimbs, which is initialized to 0 to copy the contents of the memory that the original DP points to in the new space, and releases the memory that the original DP points to.

int Bn_grow (Bignum *x, size_t nlimbs) {    bn_digit *p;    if (Nlimbs > Bn_max_limb)        return bn_exceed_max_limb;    if (Nlimbs > X->alloc)    {        p = (bn_digit *) bn_malloc (nlimbs * ciL);        if (p = = NULL) return bn_memory_allocate_fail;        memset (p, 0, Nlimbs * ciL);        if (X->DP! = NULL)    //This determines whether the BIGNUM structure's DP was allocated memory before replication and memory-release operations are made.        {            memcpy (p, X->DP, X->alloc * ciL);            memset (X->DP, 0, X->alloc * ciL);            Bn_free (X->DP);        }        X->DP = p;        X->alloc = nlimbs;    }    return 0;}

★ Copy Operation

This is very simple, copy bignum y to bignum X, note that the X->DP here points to the new memory, not to the Y->DP.

int bn_copy (bignum *x, const bignum *y) {    int ret;    size_t Nlimbs;    if (x = = y) return 0;     x = = y, which indicates that x is the same number as Y, and returns without any action at this time. Notice here that x and Y are pointers    x->sign = y->sign;    x->used = y->used;    Nlimbs = (y->used = = 0)? 1:y->used;     If Y is 0, the default is to assign X a space of    Bn_check (Bn_grow (x, Nlimbs));    memset (X->DP, 0x00, X->alloc * ciL);     Initialize Memory    if (y->dp! = NULL && y->used > 0)        memcpy (X->DP, Y->DP, y->used * ciL); clean:< C15/>return ret;}

★ Single-precision assignment operation

sometimes we want to set Bignum to a relatively small single-precision number, such as 1, 2^32-1, and so on. Assign a single-precision number to the first cell of the array by allocating a bit of memory. Here my default single-precision number is unsigned (that is, non-negative integers), if you want to assign a negative value, you can directly set sign to 1.

int Bn_set_word (bignum *x, const bn_digit word) {    int ret;    Bn_check (Bn_grow (x, 1));         Allocates a digital memory    memset (X->DP, 0, X->alloc * ciL);   Initialize    x->dp[0] = Word;    x->used = (Word! = 0)? 1:0;    X->sign = 1;      If it is negative, set sign to 1 after the function call to clean:    return ret;}

★ Exchange Operation

This function is very simple, that is, the exchange of two large integers x and y, the implementation of the principle is very simple, the exchange of the structure of each member can be.

void Bn_swap (Bignum *x, Bignum *y) {    int tmp_sign;    size_t Tmp_alloc;    size_t tmp_used;    Bn_digit *TMP_DP;    Tmp_sign = x->sign;    Tmp_alloc = x->alloc;    tmp_used = x->used;    TMP_DP = x->dp;    Y->sign = x->sign;    Y->alloc = x->alloc;    y->used = x->used;    Y->DP = x->dp;    X->sign = tmp_sign;    X->alloc = Tmp_alloc;    x->used = tmp_used;    X->DP = TMP_DP;}

★ Summary

The algorithms described in this article are the most basic algorithms in large-integer libraries, although they are the cornerstone of other algorithms, which are used frequently by the algorithms that follow. The next article will talk about how to compare two large integers, including absolute value comparisons, signed large integer comparisons, and large integers compared to single-precision numbers.

Large integer algorithm [02] basic operation (Maintenance algorithm)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.