java.lang.NoClassDefFoundError: java/util/Base64

Problem

In the following code, Base64 is used to encode AES encrypted data bytes to plain text for transfering via URL query parameter.

public static String encrypt(String strToEncrypt, String secret)
    {
        try
        {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getUrlEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
            log.warn("encryption failed", e);
        }
        return null;
    }

 

But when running this code on my coworker’s machine, following exception is thrown

java.lang.NoClassDefFoundError: java/util/Base64
	at net.redino.crypto.AES.encrypt(AES.java:49)
	at com.shopping.view.web.action.IndexViewAction.sqtx(IndexViewAction.java:947)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)

 

It’s because that my execution environment is Java 8, but my coworker is using Java 7, and java.util.Base64 is introduced in Java 8.

 

Solution

To fix this issue, we can use Base64 class from Apache Commons Codec.

First add commons codec dependency to maven pom.xml file.

<dependencies>
    ...
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>
    ...
</dependencies>

Next import Base64 class from commons-codec

import org.apache.commons.codec.binary.Base64;

 

Finally replace 

Base64.getUrlEncoder().encodeToString

to

Base64.encodeBase64URLSafeString

.

So the code will become like following

public static String encrypt(String strToEncrypt, String secret)
    {
        try
        {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.encodeBase64URLSafeString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
            log.warn("encryption failed", e);
        }
        return null;
    }

 

 

The post java.lang.NoClassDefFoundError: java/util/Base64 appeared first on Redino blog.

Source: Redino