我正在java中实现rsa和aes类,但是rsa实现有一些问题。由于我有两种不同类型的异步加密密钥,所以我创建了两种不同的方法,每种方法一种。有没有更好/更干净的方法来做到这一点?
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;
}发布于 2017-02-24 12:55:43
对于加密/解密的两种不同方法,是的,您可以将它们简化为一个函数。PrivateKey和PublicKey类都扩展了Key接口,这正是init(...)函数所需要的。
另外,请注意,您正在做一些代码风格的事情“错误”。try/catch代码应该使用更现代的具有资源的尝试机制,并且不需要在try块之外声明byte[]数组。
因此,通过改进的代码样式,将其简化为一个单一的方法,即:
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);
}
}https://codereview.stackexchange.com/questions/156048
复制相似问题