简体   繁体   English

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

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

I have RSA public and private key in two different files. 我在两个不同的文件中有RSA公钥和私钥。 This is what I've done so far. 这就是我到目前为止所做的。

    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;
  }

I have been doing it wrong. 我做错了。 I made an object(keyHolder) that holds the public and private key. 我创建了一个包含公钥和私钥的对象(keyHolder)。 And I am trying to have access to its public key by calling getPublic() method. 我试图通过调用getPublic()方法来访问其公钥。 But instead, I'd like to access my public key file directly and read its byte stream to encrypt my AES key. 但相反,我想直接访问我的公钥文件并读取其字节流以加密我的AES密钥。 How do I do that? 我怎么做?

To save the RSA public key you can simply call PublicKey.getEncoded() which returns a byte array. 要保存RSA公钥,只需调用PublicKey.getEncoded()返回一个字节数组。

To retrieve the RSA public key you would use an instance of a KeyFactory of type "RSA" and generate the public key using an X509EncodedKeySpec that accepts the same byte array. 要检索RSA公钥,您将使用类型为"RSA"KeyFactory实例,并使用接受相同字节数组的X509EncodedKeySpec生成公钥。

The rest is just normal off-the-mill binary file I/O. 其余的只是普通的现成二进制文件I / O.


The key will be saved in a DER encoded SubjectPublicKeyInfo structure as used in X509 certificate structures (hence the name of the X509EncodedKeySpec ). 密钥将保存在X509证书结构中使用的DER编码的SubjectPublicKeyInfo结构中(因此是X509EncodedKeySpec的名称)。 The PKCS#1 compatible RSA public key is embedded within that structure. PKCS#1兼容的RSA公钥嵌入在该结构中。 The additional information is used to indicate the specific key type. 附加信息用于指示特定密钥类型。

You can use openssl asn1parse -inform DER -in <publickey.der> to view the contents of the file. 您可以使用openssl asn1parse -inform DER -in <publickey.der>来查看文件的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM