我有一个静态方法用于加密和解密。我正在为这些方法编写测试但是我收到的java.lang.IllegalStateException没有初始化消息。
public final class CipherUtil {
private static Logger log = Logger.getLogger(CipherUtil.class);
private static final String SECRET_KEY = "XXX";
private static Cipher cipher;
private static SecretKeySpec secretKeySpec;
static{
try {
cipher = Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
log.error(ex);
}
byte[] key = null;
try {
key = Hex.decodeHex(SECRET_KEY.toCharArray());
} catch (DecoderException ex) {
log.error(ex);
}
secretKeySpec = new SecretKeySpec(key, "AES");
}
private CipherUtil() { }
public static String encrypt(String plainText) {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
...
}
public static String decrypt(String encryptedText) {
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
...
}
}
测试类
@Test
public void testEncryptDecrypt() {
String plainText = "Secret Message";
String encryptedText = CipherUtil.encrypt(plainText);
assertThat(encryptedText, not(equalTo(plainText)));
String decryptedText = CipherUtil.decrypt(encryptedText);
assertThat(decryptedText, is(equalTo(plainText)));
assertThat(encryptedText, not(equalTo(decryptedText)));
}
异常
java.lang.IllegalStateException: Cipher not initialized
答案 0 :(得分:0)
问题在于您无法初始化对象两次。您需要一个静态实例用于解密模式,一个用于加密模式,另一个用于您要使用的任何其他模式。您需要将init调用从方法移动到静态构造函数(尽管我同意Engineer Dollery,这不应该是静态的)。