I'm working on a client-server secure protocol where I need to use RSA in Java to encrypt a SecretKey for HMAC digests because the key has to be sent to the server. The encryption has two stages; first, I need to encrypt the symmetric key with a public asymmetric key, then, that encrypted message is encrypted with a private asymmetric key.
For this purpose I generate the SecretKey as:
public SecretKey generate(){
KeyGenerator generator = KeyGenerator.getInstance("HMACSHA256");
k = generator.generateKey();
return k;
}
Later, I use this code to encrypt any byte array with a public key:
public byte[] encryptPublic(PublicKey key, byte[] array){
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(array);
return encrypted;
}
The code for encryption with a private key is the same but using a private key.
For the RSA encryption I'm using 1024 bit long asymmetric keys so I have two main questions:
- How can I turn my SecretKey to a byte array in order to encrypt it with RSA and a public key?
- As the public key encryption produces a byte array with 128 bytes, how can I encrypt that message again with a private key if the key is 1024 bits long and can only encrypt a 117 byte long message?
getInstance()method always specify the full three-part transformation string. 2). Don't encrypt with the private key, instead perform signing. You use theSignatureclass for that. 3) Keys, including SecretKeys, have thegetEncoded()method to return a byte array representing the key in some standard format. For symmetric keys, i.e.SecretKeyinstances, the byte array returned bygetEncoded()is simply the raw key bytes. - President James K. Polk