简体   繁体   中英

Encryption of strings using AES 128 in Java/grails

I would like to encrypt 3 strings using AES 128 in Java / Grails, and using the code below, but i get the error "An error occurred when encrypting", can someone tell me what is wrong with my code, how to fix it. thanks in advance and to 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
        }
}

the error i get:

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 method call is missed in your code. Check the below code.

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);
}

For decrypt have to change mode to Cipher.DECRYPT_MODE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM