Encoding / Decoding as Base64 in Java

John Doe ·

1077 Views
package com.bad.blood.test;

import java.security.InvalidKeyException;
import java.security.Key;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;

public class LocalEncrypter {
	private static String algorithm = "DESede";
	private static Key key = null;
	private static Cipher cipher = null;
	
	private static void setUp() throws Exception {
		key = KeyGenerator.getInstance( algorithm ).generateKey();
		cipher = Cipher.getInstance( algorithm );
	}
	
	public static void main(String [] args) throws Exception {
		setUp();
		byte [] encryptionBytes = null;
		String input = "phenomena";
		System.out.println( "Entered: " + input );
		encryptionBytes = encrypt( input );
		String encodeString = new String(Base64.getEncoder().encode(encryptionBytes));
		System.out.println( "Base64 Encode: " + encodeString );
		System.out.println( "Recovered: " + decrypt( Base64.getDecoder().decode(encodeString) ) );
	}
	
	private static byte [] encrypt(String input) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
		cipher.init( Cipher.ENCRYPT_MODE, key );
		byte [] inputBytes = input.getBytes();
		return cipher.doFinal(inputBytes);
	}
	
	private static String decrypt(byte [] encryptionBytes) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        cipher.init( Cipher.DECRYPT_MODE, key );
        byte [] recoveredBytes = cipher.doFinal( encryptionBytes );
        String recovered = new String( recoveredBytes );
		return recovered;
	}
}

result:

Entered: phenomena
Base64 Encode: lfE0CaaNbx1sGUJk6dwgjQ==
Recovered: phenomena

ref. https://stackoverflow.com/questions/13109588/encoding-as-base64-in-java

 

* Image to Base64 String Conversion

package com.bad.blood.test;

import java.io.File;
import java.io.IOException;
import java.util.Base64;

import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue;

public class FileToBase64StringConversionUnitTest {

    private String inputFilePath = "test_image.jpg";
    private String outputFilePath = "test_image_copy.jpg";

    @Test
    public void fileToBase64StringConversion() throws IOException {
        // load file from /src/test/resources
        ClassLoader classLoader = getClass().getClassLoader();
        File inputFile = new File(classLoader
          .getResource(inputFilePath)
          .getFile());

        byte[] fileContent = FileUtils.readFileToByteArray(inputFile);
        String encodedString = Base64
          .getEncoder()
          .encodeToString(fileContent);

        // create output file
        File outputFile = new File(inputFile
          .getParentFile()
          .getAbsolutePath() + File.pathSeparator + outputFilePath);

        // decode the string and write to file
        byte[] decodedBytes = Base64
          .getDecoder()
          .decode(encodedString);
        FileUtils.writeByteArrayToFile(outputFile, decodedBytes);

        assertTrue(FileUtils.contentEquals(inputFile, outputFile));
    }
}

ref. https://www.baeldung.com/java-base64-image-string

base64 encode decode