簡體   English   中英

使用Java中的RSA公鑰文件加密AES密鑰

[英]encrypt AES key using RSA public key file in Java

我在兩個不同的文件中有RSA公鑰和私鑰。 這就是我到目前為止所做的。

    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密鑰。 我怎么做?

要保存RSA公鑰,只需調用PublicKey.getEncoded()返回一個字節數組。

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

其余的只是普通的現成二進制文件I / O.


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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM