2017-02-19 16 views
0

有人知道如何從編碼字節數組中創建RSA密鑰?C++/Openssl獲取來自編碼字節的RSA密鑰(由java編碼)

我的問題是,我嘗試開發一個與用Java編碼的服務器進行交互的C++客戶端。 在Java中,客戶端接收編碼爲字節數組的rsa密鑰,將其解碼爲RSA RSAPublicKey並使用此密鑰加密消息。

Java服務器/客戶端代碼:

public static PublicKey decodePublicKey(byte[] p_75896_0_) 
{ 
    try 
    { 
     X509EncodedKeySpec var1 = new X509EncodedKeySpec(p_75896_0_); 
     KeyFactory var2 = KeyFactory.getInstance("RSA"); 
     return var2.generatePublic(var1); 
    } 
    catch (NoSuchAlgorithmException var3) 
    { 
     ; 
    } 
    catch (InvalidKeySpecException var4) 
    { 
     ; 
    } 

    field_180198_a.error("Public key reconstitute failed!"); 
    return null; 
} 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

this.publicKey = CryptManager.decodePublicKey(data.readByteArray()); 

後,客戶端是做與他的關鍵部分加密的東西。

關鍵被髮送這樣的:

public static final KeyPair keys; 
static 
{ 
    try 
    { 
     KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); 
     generator.initialize(1024); 
     keys = generator.generateKeyPair(); 
    } catch (NoSuchAlgorithmException ex) 
    { 
     throw new ExceptionInInitializerError(ex); 
    } 
} 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
byte[] pubKey = keys.getPublic().getEncoded(); 
writeBytes(pubKey); 

我的問題是如何從字節數組的關鍵在C++中。

更新: 即時通訊目前正在研究這個代碼:

char* publicKey = ... 
    int publicKeyLength = 162; 
    EVP_PKEY* key = EVP_PKEY_new(); 

    if(d2i_PUBKEY(&key, (const unsigned char**) &publicKey, publicKeyLength) != 0){ 
     logError("Problem!"); 
    } 
    logMessage("Key: "+to_string((uint64_t) (void*) key)); 

現在好了,我的問題是,我有在第三行的SIGSEGV錯誤,不知道這是什麼課程。那麼關鍵應該是有效的。

+0

您是否在圖書館定居?否則,這個問題非常廣泛,因爲有很多方法可以做到這一點。 –

+0

嗯,我更喜歡OpenSSL。那麼,但如果你有更好的解決方案或庫房,我會看看這個。 –

+0

好的,您是否打開了[API文檔](https://www.openssl.org/docs/manmaster/man3/)以查看哪些功能在這種情況下可能會有所幫助? 'PEM_read_bio_PrivateKey'可能是一個很好的開始。 –

回答

0

的Java返回公鑰什麼是SubjectPublicKeyInfo進行結構,這不僅僅包含(PKCS#1編碼)的公共密鑰值,也是關鍵的標識符等

所以解碼此你必須在你最喜歡的搜索引擎中輸入「decode SubjectPublicKeyInfo openssl」。然後你會發現(後一些滾動)從here以下信息:

d2i_PUBKEY() and i2d_PUBKEY() decode and encode an EVP_PKEY structure 
using SubjectPublicKeyInfo format. They otherwise follow the conventions 
of other ASN.1 functions such as d2i_X509(). 

顯然你需要的解碼算法。


請注意,openssl是C,所以當解碼的東西時要小心緩衝區溢出。我寧願有一個1024位RSA密鑰,與安全軟件一起使用,而不是軟件充滿緩衝區溢出的2048位密鑰。

不用說你需要在導入它之前信任公鑰。有一個原因叫做公鑰基礎設施(PKI)。

+0

感謝您的詳細解答,當我在家時,我會再試一次。我已經嘗試過這種方法,但我每次都得到一個錯誤,所以我認爲java dosnt導出SubjectPublicKeyInfo結構中的密鑰。 –

+0

它當然會。確保以二進制模式打開文件。 –