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

时间:2016-12-01 08:15:52

标签: java encryption cryptography

我在两个不同的文件中有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密钥。我该怎么做?

1 个答案:

答案 0 :(得分:0)

要保存RSA公钥,您只需调用PublicKey.getEncoded()即可返回字节数组。

要检索RSA公钥,您将使用类型为KeyFactory的{​​{1}}的实例,并使用接受相同字节数组的"RSA"生成公钥。

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

密钥将保存在X509证书结构中使用的DER编码X509EncodedKeySpec结构中(因此SubjectPublicKeyInfo的名称)。 PKCS#1兼容的RSA公钥嵌入在该结构中。附加信息用于指示特定密钥类型。

您可以使用X509EncodedKeySpec查看文件内容。