在 Java/grails 中使用 AES 128 加密字符串

Encryption of strings using AES 128 in Java/grails

我想在 Java / Grails 中使用 AES 128 加密 3 个字符串,并使用下面的代码,但我收到错误 "An error occurred when encrypting",有人能告诉我我的错误吗代码,如何修复它。在此先感谢 Whosebug。

 String url = "https://someurl.com"

 String token = createToken(bookNumber, invNumber, cusNumber)

 url += '?ref=' + token

class AesEncryptor {

    static byte[] encrypt(String clearText) {
            byte[] encrypted = null
            try {
                byte[] iv = new byte[16]
                Arrays.fill(iv, (byte) 0)

                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
                encrypted = cipher.doFinal(clearText.getBytes("UTF-8"))
            }
            catch (Exception e) {
                log.error "An error occurred when encrypting", e
            }
            encrypted
        }



    /**
         * Creates a token.
         * @return
         */
        static String createToken(final String bookNumber, final String invNumber, final String cusNumber) {
            String data =  bookNumber + invNumber + cusNumber
            String token = URLEncoder.encode(Base64.encodeBase64String(encrypt(data)), "UTF-8")
            token
        }
}

我得到的错误:

java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.checkCipherState(Cipher.java:1672)
    at javax.crypto.Cipher.doFinal(Cipher.java:2079)
    at javax.crypto.Cipher$doFinal.call(Unknown Source)

cipher.init 您的代码中缺少方法调用。检查下面的代码。

public byte[] encrypt(byte[] data, byte[] key) {
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
  return cipher.doFinal(data);
}

要解密必须将模式更改为 Cipher.DECRYPT_MODE