This encryption class RSA encrypts an AES key and then when the encrypt method is called it decrypts the AES key and uses the key to encrypt the message and basically the same thing with the decryption.
However I am very very new to cryptography so I do not know if this is considered "good" or if this could be improved drastically.
--
What I would like to be reviewed:
- Is this considered secure method to cipher messages
- Is this efficient
- Is this code "clean"
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Cryptographer {
// CIPHER NECESITIES:
private KeyPairGenerator KEY_PAIR_GENERATOR;
private KeyGenerator KEY_GENERATOR;
private KeyPair RSA_KEYS;
private byte[] AES_KEY_DATA;
private Cipher AESKeyEncryptor;
private Cipher MessageEncryptor;
private IvParameterSpec Iv = new IvParameterSpec(SecureRandom.getSeed(16));
// SETTINGS:
final private int RSA_KEY_SIZE = 2048;
final private int AES_KEY_SIZE = 256;
final private String RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
final private String AES_ALGORITHM = "AES/CBC/PKCS5PADDING";
// CONSTRUCTOR:
public Cryptographer() throws Exception {
KEY_PAIR_GENERATOR = KeyPairGenerator.getInstance("RSA");
KEY_GENERATOR = KeyGenerator.getInstance("AES");
KEY_PAIR_GENERATOR.initialize(RSA_KEY_SIZE);
KEY_GENERATOR.init(AES_KEY_SIZE);
RSA_KEYS = KEY_PAIR_GENERATOR.generateKeyPair();
MessageEncryptor = Cipher.getInstance(AES_ALGORITHM);
AESKeyEncryptor = Cipher.getInstance(RSA_ALGORITHM);
AES_KEY_DATA = EncryptAESKey(KEY_GENERATOR.generateKey());
}
// PRIVATE METHODS:
private byte[] EncryptAESKey(SecretKey key) throws Exception {
AESKeyEncryptor.init(Cipher.ENCRYPT_MODE, RSA_KEYS.getPublic());
return AESKeyEncryptor.doFinal(
key.getEncoded()
);
}
private SecretKey DecryptAESKey(byte[] EncryptedAESKey) throws Exception {
AESKeyEncryptor.init(Cipher.DECRYPT_MODE, RSA_KEYS.getPrivate());
return new SecretKeySpec(
AESKeyEncryptor.doFinal(EncryptedAESKey),
"AES"
);
}
// PUBLIC METHODS:
public byte[] Encrypt(byte[] message) throws Exception {
MessageEncryptor.init(Cipher.ENCRYPT_MODE, DecryptAESKey(AES_KEY_DATA), Iv);
return MessageEncryptor.doFinal(message);
}
public byte[] Decrypt(byte[] message) throws Exception {
MessageEncryptor.init(Cipher.DECRYPT_MODE, DecryptAESKey(AES_KEY_DATA), Iv);
return MessageEncryptor.doFinal(message);
}
}
```