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

时间:2015-06-19 07:57:44

标签: java grails encryption aes

我想在Java / Grails中使用AES 128加密3个字符串,并使用下面的代码,但我得到错误"加密时发生错误",有人可以告诉我有什么问题吗?我的代码,如何解决它。提前感谢Stackoverflow。

 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$1.call(Unknown Source)

1 个答案:

答案 0 :(得分:2)

您的代码中错过了

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