I'm implementing rsa and aes classes in java, but i have some trouble with the rsa implementation. Since i have two keys in asymetric encryption, with two different types, i've made two differents methods, one for each. Is there a better/cleaner way to do that?
private static byte[] doCrypto(
int cipherMode,
PublicKey publicKey,
byte[] inputBytes)
throws CryptoException {
Cipher cipher;
byte[] outputBytes;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(cipherMode, publicKey);
outputBytes = cipher.doFinal(inputBytes);
} catch (NoSuchPaddingException
| NoSuchAlgorithmException
| InvalidKeyException
| BadPaddingException
| IllegalBlockSizeException ex) {
throw new CryptoException("Error doCrypto", ex);
}
return outputBytes;
}
private static byte[] doCrypto(
int cipherMode,
PrivateKey privateKey,
byte[] inputBytes)
throws CryptoException {
Cipher cipher;
byte[] outputBytes;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(cipherMode, privateKey);
outputBytes = cipher.doFinal(inputBytes);
} catch (NoSuchPaddingException
| NoSuchAlgorithmException
| InvalidKeyException
| BadPaddingException
| IllegalBlockSizeException ex) {
throw new CryptoException("Error doCrypto", ex);
}
return outputBytes;
}
1 Answer 1
Regarding the two different methods for the encrypt/decrypt, yes, you can reduce them to just one function. The PrivateKey
and PublicKey
classes both extend the Key
interface, and that's what's needed for the init(...)
function.
Note also, that you are doing some code-style things "wrong". Your try/catch code should be using the more modern try-with-resources mechanism, and there's no need to declare the byte[]
array outside the try block.
So, reducing it all down to a single method, with improved code style, it would be:
private static byte[] doCrypto(int cipherMode, Key key, byte[] inputBytes)
throws CryptoException {
try (Cipher cipher = Cipher.getInstance("RSA")) {
cipher.init(cipherMode, key);
return cipher.doFinal(inputBytes);
} catch (NoSuchPaddingException
| NoSuchAlgorithmException
| InvalidKeyException
| BadPaddingException
| IllegalBlockSizeException ex) {
throw new CryptoException("Error doCrypto", ex);
}
}
-
\$\begingroup\$ I'll read a bit on "try-with-resources mechanism". Thanks a lot for your advices, I'll remember them! ;) \$\endgroup\$moKa– moKa2017年02月25日 01:47:30 +00:00Commented Feb 25, 2017 at 1:47