RSA ... GNU MP:无法分配内存(size = 1307836444)

时间:2013-11-21 16:56:54

标签: c++ encryption rsa gmp

首先,我正在运行Ubuntu 12.04 32位。该程序通过将 cin 加入char缓冲区来执行RSA pub密钥加密。然后,当我调用我的加密函数时,我收到以下错误:

GNU MP: Cannot allocate memory (size=1307836444)
Aborted (core dumped)

当我更改我生成的 p,q 键的位大小时,此运行时错误的大小会增加。只有在我调用 encrypt()

后才会出现此错误
void generate_pq(mpz_t p, mpz_t q);
void compute_n(mpz_t n, const mpz_t p, const mpz_t q);
void compute_phiN(mpz_t phi_n, const mpz_t p, const mpz_t q);
void select_e(mpz_t e, mpz_t phi_n);
void compute_d(mpz_t d, mpz_t e, mpz_t phi_n);
void store_m(mpz_t m[], int& size);
void encrypt(mpz_t c[], mpz_t m[], const int size, 
                 const mpz_t e, const mpz_t n);
void decrypt(mpz_t m2[], mpz_t c[], const int size, 
                 const mpz_t d, const mpz_t n);

int main() 
{
    mpz_t p, q, n, phi_n, e, d; 
    mpz_inits(p, q, n, phi_n, e, d, NULL);

    // 1. Generate p,q; compute n
    generate_pq(p,q);
    compute_n(n,p,q);
    // 2. Compute phi(n)=(p-1)*(q-1)
    compute_phiN(phi_n,p,q);
    mpz_clear(p); mpz_clear(q);
    // 3. Select encryption key e
    select_e(e,phi_n);
    // 4. Compute decryption key d
    compute_d(d,e,phi_n);
    // 5. m = message to be encrypted
    mpz_t* m;
    int size=0;
    store_m(m,size);
    // 6. c = encrypted message
    mpz_t* c;
    encrypt(c,m,size,e,n);
    // 7. m2 = decrypted message 
    //mpz_t* m2;
    //decrypt(m2,c,size,d,n);
    return 0;
}

使用...编译

g++ -o rsa partb.cc -lgmpxx -lgmp

我尝试在m,c和m2的for循环中使用mpz_clear。没变。这是加密功能:

void store_m(mpz_t m[], int& size) 
{
    printf("Message: ");
    char* buffer = new char[128];
    cin.getline(buffer,128);
    size = strlen(buffer); //size = buffer
    m = new mpz_t[size];
    for(int i=0; i<size; i++) {
        mpz_init(m[i]);
        mpz_set_ui(m[i],(int)buffer[i]);
    }
}

void encrypt(mpz_t c[], mpz_t m[], const int size, 
                 const mpz_t e, const mpz_t n)
{ /* c = cipher */
    c = new mpz_t[size];
    for(int i=0; i<size; i++) {
        mpz_init(c[i]);
        mpz_powm(c[i],m[i],e,n);
        mpz_clear(m[i]);
    } /* c = m^e(mod n) */
}

也许问题是我没有释放足够的已经声明和初始化的mpz_t?我尝试清除2或3个mpz_t,但它似乎没有效果。请指教。

修改!!!!!!!!

将seg错误隔离到此语句:

mpz_powm(c[i],m[i],e,n);

1 个答案:

答案 0 :(得分:1)

mpz_t* c函数不会更改您的变量encrypt,因此在encrypt返回后它仍指向随机(可能无效)地址。请尝试改为:

void encrypt(mpz_t*& c,...