2015-12-08 123 views
0

我有一個與RSA_public_encrypt加密問題。與RSA_public_encrypt OpenSSL問題

我有什麼:模數(1024位),指數(每次他們不改變)和明文。

我想要的是:使用RSA_PKCS1_OAEP_PADDING作爲模數和指數(作爲十六進制字符串傳遞)的公鑰對純文本進行加密。

問題是,RSA_public_encrypt函數會導致訪問衝突,我不明白爲什麼。我在互聯網上看到了很多類似的例子,但由於評論意見,它們似乎很好。

這裏是我的代碼:

procedure RSAPublicEncrypt(const PlainText, Modulus, Exponent: AnsiString); 
    var 
    PublicKey: pRSA; 
    Output: Integer; 
    BN_Modulus, BN_Exponent: pBIGNUM; 
    Res: AnsiString; 
    begin 
    Result := ''; 
    try 
     PublicKey := RSA_new(); //Creating new key 

     PublicKey^.n := BN_new; //Creating new modulus 
     Output := BN_hex2bn(PublicKey^.n, PAnsiChar(Modulus)); //Convert modulut from hex to BIGNUM 

     PublicKey^.e := BN_new; //same to the exponent 
     BN_hex2bn(PublicKey^.e, PAnsiChar(Exponent)); 

     //Trying to encrypt. Here I get the AV 
     Output := RSA_public_encrypt(Length(PlainText), PAnsiChar(PlainText), PAnsiChar(Res), PublicKey, RSA_PKCS1_OAEP_PADDING); 
    finally 
     BN_clear_free(PublicKey^.e); 
     BN_clear_free(PublicKey^.n); 
     RSA_free(PublicKey); 
    end; 
    end; 

我在做什麼錯?請幫幫我。提前致謝!

回答

0

最後我找到了問題的根源。這是RSA結構的錯誤實現。它缺少一個指針:

RSA = record 
    pad: integer; 
    version: integer; 
    meth: pRSA_METHOD; 
    engine: pointer; //<-- this one was missing 
    n: pBIGNUM; 
    e: pBIGNUM; 
    d: pBIGNUM; 
    p: pBIGNUM; 
    q: pBIGNUM; 
    dmp1: pBIGNUM; 
    dmq1: pBIGNUM; 
    iqmp: pBIGNUM; 
    ex_data: CRYPTO_EX_DATA; 
    references: integer; 
    flags: integer; 
    _method_mod_n: pBN_MONT_CTX; 
    _method_mod_p: pBN_MONT_CTX; 
    _method_mod_q: pBN_MONT_CTX; 
    bignum_data: ^byte; 
    blinding: ^BN_BLINDING; 
end; 
0

Res未初始化,但您正在寫入。我認爲一個錯字和線

Result := ''; 

真的應該

Res := ''; 

如果是這樣,那麼沒有足夠的空間來容納你的結果,你需要使用類似SetLength水庫至使其足夠大以保持結果加上一個空終止符。

SetLength(Res, Length(PlainText) + 1); // or whatever is appropriate 

你需要知道的是AnsiString類型是引用計數和自動控制像一個正常的字符串,但PAnsiChar也沒有了,認爲不會自動改變其大小(分配的內存)一個預定義的字符串。當您將AnsiString強制轉換爲PAnsiChar時,編譯器在內部將一個指針傳遞給AnsiString的第一個字符,繞過其引用計數和長度字段。它不會將Res更改爲AnsiChar陣列。因此必須非常小心地使用它。

的另一種方式是定義作爲RES ANSIChar類型

Res : Array[0..255] of AnsiChar; 

的例如陣列,其中明確示出了所分配的存儲器,但設置長度爲更加靈活。