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

标签 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)

最佳答案

您的代码中缺少 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

关于java - 在 Java/grails 中使用 AES 128 加密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30932939/

相关文章:

java - android 不压缩保存位图

grails - 将 Grails 与 Spring Social(Facebook、Twitter 和 Google)集成需要什么

php - 如何在 php 中解密散列密码?使用 password_hash() 方法散列的密码

java - 使用 groovy 的 toURL 方法忽略 SSL 错误

PHP AES 加密 PKCS5Padding

c# - 将 java sha512crypt 转换为 c#

java - 应用程序的大小,如何确定

java - 从网格布局到GridBagLayout

java - Cassandra-Hector 单节点集群 HUnavailableException : : May not be enough replicas present to handle consistency level

grails - grails 2中的PagedResultList问题