2016-12-01 212 views
1

我在兩個不同的文件中有RSA公鑰和私鑰。 這就是我迄今爲止所做的。使用Java中的RSA公鑰文件加密AES密鑰

public SecretKey getAESkey() throws Exception, NoSuchAlgorithmException{   
     KeyGenerator generator = KeyGenerator.getInstance("AES"); 
     generator.init(128); 
     SecretKey sKey = generator.generateKey(); 
     return sKey; // will be passed to encryptSecretKey method 
    } 

    public byte[] encryptSecretKey (SecretKey sKey) 
    { 
     Cipher cipher = null; 
     byte[] key = null; 

     try 
     { 
     // initialize the cipher with the user's public key 
     cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
     cipher.init(Cipher.ENCRYPT_MODE, keyHolder.keyPair.getPublic()); 
     key = cipher.doFinal(sKey.getEncoded()); 
     } 
     catch(Exception e) 
     { 
     e.printStackTrace(); 
     } 
     return key; 
    } 

我一直在做錯了。我做了一個持有公鑰和私鑰的對象(keyHolder)。我試圖通過調用getPublic()方法來訪問其公鑰。但是,我想直接訪問我的公鑰文件並讀取它的字節流來加密我的AES密鑰。我怎麼做?

回答

0

要保存RSA公鑰,您可以簡單地調用PublicKey.getEncoded(),它返回一個字節數組。

要檢索RSA公鑰,您將使用"RSA"類型的KeyFactory的實例,並使用接受相同字節數組的X509EncodedKeySpec生成公鑰。

其餘的只是普通的二進制文件I/O。


密鑰將被保存在一個DER編碼SubjectPublicKeyInfo結構如X509證書結構中使用(在X509EncodedKeySpec因此得名)。 PKCS#1兼容的RSA公鑰嵌入在該結構中。附加信息用於指示特定的密鑰類型。

您可以使用openssl asn1parse -inform DER -in <publickey.der>來查看文件的內容。