2016-12-01 214 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>来查看文件的内容。