在Java中使用RSA公钥文件加密AES密钥
我在两个不同的文件中有RSA公钥和私钥。 这就是我到目前为止所做的在Java中使用RSA公钥文件加密AES密钥,java,encryption,cryptography,Java,Encryption,Cryptography,我在两个不同的文件中有RSA公钥和私钥。 这就是我到目前为止所做的 public SecretKey getAESkey() throws Exception, NoSuchAlgorithmException{ KeyGenerator generator = KeyGenerator.getInstance("AES"); generator.init(128); SecretKey sKey = generator.generat
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
查看文件内容。要保存RSA公钥,只需调用PublicKey.getEncoded()
,返回字节数组即可
要检索RSA公钥,您需要使用类型为“RSA”的KeyFactory
的实例,并使用接受相同字节数组的X509EncodedKeySpec
生成公钥
其余的只是普通的非常规二进制文件I/O
密钥将保存在X509证书结构中使用的DER编码的
SubjectPublicKeyInfo
结构中(因此命名为X509EncodedKeySpec
)。PKCS#1兼容的RSA公钥嵌入在该结构中。附加信息用于指示特定的密钥类型
您可以使用openssl asn1parse-inform DER-in
查看文件内容